- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- springsecurity如何實(shí)現登錄注銷(xiāo)功能
這篇文章將為大家詳細講解有關(guān)springsecurity如何實(shí)現登錄注銷(xiāo)功能,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
1、引入maven依賴(lài)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
2、Security 配置類(lèi) 說(shuō)明登錄方式、登錄頁(yè)面、哪個(gè)url需要認證、注入登錄失敗/成功過(guò)濾器
@Configurationpublic class BrowserSecurityConfig extends WebSecurityConfigurerAdapter { /** * 注入 Security 屬性類(lèi)配置 */ @Autowired private SecurityProperties securityProperties; /** * 注入 自定義的 登錄成功處理類(lèi) */ @Autowired private MyAuthenticationSuccessHandler mySuccessHandler; /** * 注入 自定義的 登錄失敗處理類(lèi) */ @Autowired private MyAuthenticationFailHandler myFailHandler; /** * 重寫(xiě)PasswordEncoder 接口中的方法,實(shí)例化加密策略 * @return 返回 BCrypt 加密策略 */ @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { //登錄成功的頁(yè)面地址 String redirectUrl = securityProperties.getLoginPage(); //basic 登錄方式// http.httpBasic() //表單登錄 方式 http.formLogin() .loginPage("/authentication/require") //登錄需要經(jīng)過(guò)的url請求 .loginProcessingUrl("/authentication/form") .successHandler(mySuccessHandler) .failureHandler(myFailHandler) .and() //請求授權 .authorizeRequests() //不需要權限認證的url .antMatchers("/authentication/*",redirectUrl).permitAll() //任何請求 .anyRequest() //需要身份認證 .authenticated() .and() //關(guān)閉跨站請求防護 .csrf().disable(); //默認注銷(xiāo)地址:/logout http.logout(). //注銷(xiāo)之后 跳轉的頁(yè)面 logoutSuccessUrl("/authentication/require"); }
3、自定義登錄成功和失敗的處理器
(1)、登錄成功
@Component@Slf4jpublic class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { logger.info("登錄成功"); //將 authention 信息打包成json格式返回 httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().write("登錄成功"); } }
(2)、登錄失敗
@Component@Slf4jpublic class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { logger.info("登錄失敗"); //設置狀態(tài)碼 httpServletResponse.setStatus(500); //將 登錄失敗 信息打包成json格式返回 httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().write("登錄失?。?quot;+e.getMessage()); } }
4、UserDetail 類(lèi) 加載用戶(hù)數據 , 返回UserDetail 實(shí)例 (里面包含用戶(hù)信息)
@Component@Slf4jpublic class MyUserDetailsService implements UserDetailsService { @Autowired private PasswordEncoder passwordEncoder; /** * 根據進(jìn)行登錄 * @param username * @return * @throws UsernameNotFoundException */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { log.info("登錄用戶(hù)名:"+username); String password = passwordEncoder.encode("123456"); //User三個(gè)參數 (用戶(hù)名+密碼+權限) //根據查找到的用戶(hù)信息判斷用戶(hù)是否被凍結 log.info("數據庫密碼:"+password); return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")); }}
5、登錄路徑請求類(lèi),.loginPage("/authentication/require")
@RestController@Slf4j@ResponseStatus(code = HttpStatus.UNAUTHORIZED)public class BrowerSecurityController { /** * 把當前的請求緩存到 session 里去 */ private RequestCache requestCache = new HttpSessionRequestCache(); /** * 重定向 策略 */ private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); /** * 注入 Security 屬性類(lèi)配置 */ @Autowired private SecurityProperties securityProperties; /** * 當需要身份認證時(shí) 跳轉到這里 */ @RequestMapping("/authentication/require") public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException { //拿到請求對象 SavedRequest savedRequest = requestCache.getRequest(request, response); if (savedRequest != null){ //獲取 跳轉url String targetUrl = savedRequest.getRedirectUrl(); log.info("引發(fā)跳轉的請求是:"+targetUrl); //判斷 targetUrl 是不是 .html 結尾, 如果是:跳轉到登錄頁(yè)(返回view) if (StringUtils.endsWithIgnoreCase(targetUrl,".html")){ String redirectUrl = securityProperties.getLoginPage(); redirectStrategy.sendRedirect(request,response,redirectUrl); } } //如果不是,返回一個(gè)json 字符串 return new SimpleResponse("訪(fǎng)問(wèn)的服務(wù)需要身份認證,請引導用戶(hù)到登錄頁(yè)"); }
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站