![](/img/trans.png)
[英]SpringBoot 2.2.2: Jackson serializer for custom pagination doesn't work
[英]SpringSecurity custom login functionality doesn't work with SpringBoot and REST api
我嘗試使用自定義登錄頁面實現登錄功能,但不幸的是它不起作用..我也找不到原因..可能我不完全理解SpringSecurity機制。 看起來提交按鈕什么都不做。 我的代碼如下。 我將非常樂意提供幫助。
登錄.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>test login page</h1>
<form name="login" action="/login" method="post">
User: <input type="text" name="username"/>
Password: <input type="password" name="password"/>
<input name="submit" type="submit" value="LOGIN"/>
<hr>
<button id="loginAsGuest">Login as a guest</button>
</form>
</body>
</html>
網絡安全配置.java:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}admin").roles("ADMIN")
.and()
.withUser("userguest").password("{noop}userguest").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/").hasAnyRole("ADMIN")
.antMatchers("/").hasAnyRole("USER")
.antMatchers("/login*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login.html")
.defaultSuccessUrl("/bookmarks-app/index.html", true)
.failureUrl("/login.html")
.and()
.logout().permitAll().logoutRequestMatcher(new AntPathRequestMatcher("/logout")
);
}
}
只是指出一些事情。
hasAnyRole支持多個角色,所以你可以這樣寫.antMatchers("/**").hasAnyRole("ADMIN", "USER")
如果你放 /** 每個 rest 服務都會觸發角色檢查,如果你放 / 只有 / rest 服務會觸發檢查。
刪除.antMatchers("/login*").permitAll()
並將.loginPage("/login.html")
替換為.loginPage("/login").permitAll()
最后,您的配置將如下所示:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/**").hasAnyRole("ADMIN", "USER")
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login.html").permitAll().loginProcessingUrl("/perform_login")
//No need to add a LoginController.
// Needed because if you don't put this, when you call the POST to login you will be redirected to the login.html page.
.defaultSuccessUrl("/bookmarks-app/index.html", true)
.failureUrl("/login.html").permitAll()
.and()
.logout().permitAll().logoutRequestMatcher(new AntPathRequestMatcher("/logout")
);
}
如果您的登錄頁面在資源中,請不要忘記正確配置 ResourceHandler。
資料來源:
https://docs.spring.io/spring-security/site/docs/4.1.3.RELEASE/guides/html5/form-javaconfig.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.