溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

springsecurity如何實現(xiàn)登錄注銷功能

發(fā)布時間:2021-09-27 15:35:13 來源:億速云 閱讀:141 作者:小新 欄目:編程語言

這篇文章將為大家詳細講解有關(guān)springsecurity如何實現(xiàn)登錄注銷功能,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

1、引入maven依賴

<dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-security</artifactId>    </dependency>

2、Security 配置類 說明登錄方式、登錄頁面、哪個url需要認證、注入登錄失敗/成功過濾器

@Configurationpublic class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {  /**   * 注入 Security 屬性類配置   */  @Autowired  private SecurityProperties securityProperties;  /**   * 注入 自定義的 登錄成功處理類   */  @Autowired  private MyAuthenticationSuccessHandler mySuccessHandler;  /**   * 注入 自定義的 登錄失敗處理類   */  @Autowired  private MyAuthenticationFailHandler myFailHandler;  /**   * 重寫PasswordEncoder 接口中的方法,實例化加密策略   * @return 返回 BCrypt 加密策略   */  @Bean  public PasswordEncoder passwordEncoder(){    return new BCryptPasswordEncoder();  }  @Override  protected void configure(HttpSecurity http) throws Exception {    //登錄成功的頁面地址    String redirectUrl = securityProperties.getLoginPage();    //basic 登錄方式//   http.httpBasic()    //表單登錄 方式    http.formLogin()        .loginPage("/authentication/require")        //登錄需要經(jīng)過的url請求        .loginProcessingUrl("/authentication/form")        .successHandler(mySuccessHandler)        .failureHandler(myFailHandler)        .and()        //請求授權(quán)        .authorizeRequests()        //不需要權(quán)限認證的url        .antMatchers("/authentication/*",redirectUrl).permitAll()        //任何請求        .anyRequest()        //需要身份認證        .authenticated()        .and()        //關(guān)閉跨站請求防護        .csrf().disable();    //默認注銷地址:/logout    http.logout().        //注銷之后 跳轉(zhuǎn)的頁面        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("登錄失敗");      //設(shè)置狀態(tài)碼      httpServletResponse.setStatus(500);      //將 登錄失敗 信息打包成json格式返回      httpServletResponse.setContentType("application/json;charset=UTF-8");      httpServletResponse.getWriter().write("登錄失?。?quot;+e.getMessage()); } }

4、UserDetail 類 加載用戶數(shù)據(jù) , 返回UserDetail 實例 (里面包含用戶信息)

@Component@Slf4jpublic class MyUserDetailsService implements UserDetailsService {  @Autowired  private PasswordEncoder passwordEncoder;  /**   * 根據(jù)進行登錄   * @param username   * @return   * @throws UsernameNotFoundException   */  @Override  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {    log.info("登錄用戶名:"+username);    String password = passwordEncoder.encode("123456");    //User三個參數(shù)  (用戶名+密碼+權(quán)限)    //根據(jù)查找到的用戶信息判斷用戶是否被凍結(jié)    log.info("數(shù)據(jù)庫密碼:"+password);    return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));  }}

5、登錄路徑請求類,.loginPage("/authentication/require")

@RestController@Slf4j@ResponseStatus(code = HttpStatus.UNAUTHORIZED)public class BrowerSecurityController {  /**   * 把當前的請求緩存到 session 里去   */  private RequestCache requestCache = new HttpSessionRequestCache();  /**   * 重定向 策略   */  private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();  /**   * 注入 Security 屬性類配置   */  @Autowired  private SecurityProperties securityProperties;  /**   * 當需要身份認證時 跳轉(zhuǎn)到這里   */  @RequestMapping("/authentication/require")  public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {    //拿到請求對象    SavedRequest savedRequest = requestCache.getRequest(request, response);    if (savedRequest != null){      //獲取 跳轉(zhuǎn)url      String targetUrl = savedRequest.getRedirectUrl();      log.info("引發(fā)跳轉(zhuǎn)的請求是:"+targetUrl);      //判斷 targetUrl 是不是 .html 結(jié)尾, 如果是:跳轉(zhuǎn)到登錄頁(返回view)      if (StringUtils.endsWithIgnoreCase(targetUrl,".html")){        String redirectUrl = securityProperties.getLoginPage();        redirectStrategy.sendRedirect(request,response,redirectUrl);      }    }    //如果不是,返回一個json 字符串    return new SimpleResponse("訪問的服務(wù)需要身份認證,請引導(dǎo)用戶到登錄頁");  }

關(guān)于“springsecurity如何實現(xiàn)登錄注銷功能”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI