@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
// 指定密碼的加密方式
@SuppressWarnings ( "deprecation" )
@Bean
PasswordEncoder passwordEncoder(){
// 不對密碼進行加密
return NoOpPasswordEncoder.getInstance();
}
// 配置用戶及其對應的角色
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser( "root" ).password( "123" ).roles( "DBA" )
.and()
.withUser( "admin" ).password( "123" ).roles( "ADMIN" )
.and()
.withUser( "hangge" ).password( "123" ).roles( "USER" );
}
// 配置 URL 訪問權限
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() // 開啓 HttpSecurity 配置
.antMatchers( "/db/**" ).hasRole( "DBA" ) // db/** 模式URL需DBA角色
.antMatchers( "/admin/**" ).hasRole( "ADMIN" ) // admin/** 模式URL需ADMIN角色
.antMatchers( "/user/**" ).hasRole( "USER" ) // user/** 模式URL需USER角色
.anyRequest().authenticated() // 用戶訪問其它URL都必須認證後訪問(登錄後訪問)
.and().formLogin().loginProcessingUrl( "/login" ).permitAll() // 開啓表單登錄並配置登錄接口
.and().logout() // 開啓註銷登錄的配置
.logoutUrl( "/logout" ) // 配置註銷登錄請求URL爲"/logout"(默認也就是 /logout)
.clearAuthentication( true ) // 清除身份認證信息
.invalidateHttpSession( true ) // 使 session 失效
// 配置一個 LogoutHandler,開發者可以在這裏完成一些數據清除工做
.addLogoutHandler( new LogoutHandler() {
@Override
public void logout(HttpServletRequest req,
HttpServletResponse resp,
Authentication auth) {
System.out.println( "註銷登錄,開始清除Cookie。" );
}
})
// 配置一個 LogoutSuccessHandler,開發者可以在這裏處理註銷成功後的業務邏輯
.logoutSuccessHandler( new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest req,
HttpServletResponse resp,
Authentication auth)
throws IOException, ServletException {
// 我們可以跳轉到登錄頁面
// resp.sendRedirect("/login");
// 也可以返回一段JSON提示
resp.setContentType( "application/json;charset=utf-8" );
PrintWriter out = resp.getWriter();
resp.setStatus( 200 );
Map<String, Object> map = new HashMap<>();
map.put( "status" , 200 );
map.put( "msg" , "註銷成功!" );
ObjectMapper om = new ObjectMapper();
out.write(om.writeValueAsString(map));
out.flush();
out.close();
}
})
.and().csrf().disable(); // 關閉csrf
}
}
|