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

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

為吳橋等地區(qū)用戶提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及吳橋網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)、吳橋網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!

1、引入maven依賴

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

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

@Configurationpublic class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {  /**   * 注入 Security 屬性類配置   */  @Autowired  private SecurityProperties securityProperties;  /**   * 注入 自定義的 登錄成功處理類   */  @Autowired  private MyAuthenticationSuccessHandler mySuccessHandler;  /**   * 注入 自定義的 登錄失敗處理類   */  @Autowired  private MyAuthenticationFailHandler myFailHandler;  /**   * 重寫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)過的url請(qǐng)求        .loginProcessingUrl("/authentication/form")        .successHandler(mySuccessHandler)        .failureHandler(myFailHandler)        .and()        //請(qǐng)求授權(quán)        .authorizeRequests()        //不需要權(quán)限認(rèn)證的url        .antMatchers("/authentication/*",redirectUrl).permitAll()        //任何請(qǐng)求        .anyRequest()        //需要身份認(rèn)證        .authenticated()        .and()        //關(guān)閉跨站請(qǐng)求防護(hù)        .csrf().disable();    //默認(rèn)注銷地址:/logout    http.logout().        //注銷之后 跳轉(zhuǎn)的頁(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("登錄失敗");      //設(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 實(shí)例 (里面包含用戶信息)

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

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

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

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

分享名稱:springsecurity如何實(shí)現(xiàn)登錄注銷功能
網(wǎng)頁(yè)地址:http://bm7419.com/article8/iipgop.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化、自適應(yīng)網(wǎng)站移動(dòng)網(wǎng)站建設(shè)、小程序開發(fā)、網(wǎng)站改版、ChatGPT

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都seo排名網(wǎng)站優(yōu)化