配置文件
@EnableWebSecurity
public class SercurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
//请求授权的规则
http.authorizeRequests()
.antMatchers("/","/asserts/**","/webjars/**","/error/**","/index").permitAll()
.anyRequest().authenticated()//所有请求登录后可以访问
.and()
.formLogin()//表单登录
.loginPage("/")//指定登录页面
.defaultSuccessUrl("/emps")//登陆成功后的页面
.loginProcessingUrl("/login")//登陆请求url
.permitAll()
.and()
.logout()//开启logout注销功能,发送请求logout会注销并清空session
.logoutUrl("/custom-logout")//注销的请求url
.logoutSuccessUrl("/")//注销后的地址
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(new PasswordEncoder() {
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return true;
}
});
}
}
登录页面表单
<form class="form-signin" th:action="@{/login}" method="post">
<img class="mb-4" th:src="@{asserts/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<!--显示错误消息-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<label class="sr-only">Username</label>
<input type="text" class="form-control" name="username" th:placeholder="#{login.userName}" required="" autofocus="">
<label class="sr-only">Password</label>
<input type="password" class="form-control" name="password" th:placeholder="#{login.passWord}" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"/>[[#{login.remember}]]
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.signin}">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm" th:href="@{/index(l='zh_CN')}" >中文</a>
<a class="btn btn-sm" th:href="@{/index(l='en_US')}">English</a>
</form>
注销
默认是开启csrf的,所以要使用post,并且需要传入一个登录后产生的token
<form id="logoutForm" action="/custom-logout" method="post">
<input type="hidden" th:name="${_csrf.getParameterName()}" th:value="${_csrf.getToken()}">
<button type="submit" class="nav-link logoutBtn">Sign out</button>
</form>