public class MyUser implements Serializable {
private static final long serialVersionUID = 3497935890426858541L;
private String userName;
private String password;
private boolean accountNonExpired = true;
private boolean accountNonLocked= true;
private boolean credentialsNonExpired= true;
private boolean enabled= true;
// get,set略,推薦使用快捷鍵生成
- UserDetailService: 實現UserDetailsService接口
@Configuration
public class UserDetailService implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 模擬一個用戶,替代數據庫獲取邏輯
MyUser user = new MyUser();
user.setUserName(username);
user.setPassword(this.passwordEncoder.encode("123456"));
// 輸出加密後的密碼
System.out.println(user.getPassword());
return new User(username, user.getPassword(), user.isEnabled(),
user.isAccountNonExpired(), user.isCredentialsNonExpired(),
user.isAccountNonLocked(), AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
}
- IndexController:跳轉到index頁面控制器
@RestController
public class IndexController {
@GetMapping("index")
public Object index(){
return SecurityContextHolder.getContext().getAuthentication();
}
}
- MySecurityController:是否能訪問靜態資源的控制器
@RestController
public class MySecurityController {
//RequestCache requestCache是Spring Security提供的用於緩存請求的對象
private RequestCache requestCache = new HttpSessionRequestCache();
//DefaultRedirectStrategy是Spring Security提供的重定向策略
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@GetMapping("/authentication/require")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
//getRequest方法能夠獲取到本次請求的HTTP信息
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null) {
String targetUrl = savedRequest.getRedirectUrl();
if (StringUtils.endsWithIgnoreCase(targetUrl, ".html"))
//sendRedirect爲Spring Security提供的用於處理重定向的方法
redirectStrategy.sendRedirect(request, response, "/login.html");
}
return "訪問的資源須要身份認證!";
}
}
- MySecurityConfig:SpringSecurity的配置類
@Component
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationFailureHandler authenticationFailureHandler;
@Autowired
private MyAuthenticationSuccessHandler authenticationSuccessHandler;
@Autowired
private ValidateCodeFilter validateCodeFilter;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() // 表單登陸
// http.httpBasic() // HTTP Basic
.loginPage("/authentication/require") // 登陸跳轉 URL
.loginProcessingUrl("/login") // 處理表單登陸 URL
.failureHandler(authenticationFailureHandler) // 處理登陸失敗
.successHandler(authenticationSuccessHandler)
.and()
.authorizeRequests() // 受權配置
.antMatchers("/authentication/require",
"/login.html").permitAll() // 無需認證的請求路徑
.anyRequest() // 全部請求
.authenticated() // 都須要認證
.and().csrf().disable();
}
}
- MyAuthenticationFailureHandler:請求失敗的配置類(在SpringSecurity的配置類中使用)
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Autowired
private ObjectMapper mapper;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(mapper.writeValueAsString(exception.getMessage()));
}
}
- MyAuthenticationSuccessHandler:請求成功的配置類(在SpringSecurity的配置類中使用)
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
redirectStrategy.sendRedirect(request, response, "/index");
}
}