91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

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

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

怎么在SpringSecurity中利用JWT實現一個前后端分離功能

發布時間:2021-01-20 13:52:50 來源:億速云 閱讀:362 作者:Leah 欄目:開發技術

這篇文章將為大家詳細講解有關怎么在SpringSecurity中利用JWT實現一個前后端分離功能,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。

創建一個配置類 SecurityConfig 繼承 WebSecurityConfigurerAdapter

package top.ryzeyang.demo.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import top.ryzeyang.demo.common.filter.JwtAuthenticationTokenFilter;
import top.ryzeyang.demo.utils.JwtTokenUtil;


@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  final AuthenticationFailureHandler authenticationFailureHandler;
  final AuthenticationSuccessHandler authenticationSuccessHandler;
  final AuthenticationEntryPoint authenticationEntryPoint;
  final AccessDeniedHandler accessDeniedHandler;
  final LogoutSuccessHandler logoutSuccessHandler;

  public SecurityConfig(AuthenticationFailureHandler authenticationFailureHandler, AuthenticationSuccessHandler authenticationSuccessHandler, AuthenticationEntryPoint authenticationEntryPoint, AccessDeniedHandler accessDeniedHandler, LogoutSuccessHandler logoutSuccessHandler) {
    this.authenticationFailureHandler = authenticationFailureHandler;
    this.authenticationSuccessHandler = authenticationSuccessHandler;
    this.authenticationEntryPoint = authenticationEntryPoint;
    this.accessDeniedHandler = accessDeniedHandler;
    this.logoutSuccessHandler = logoutSuccessHandler;
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
  }

  @Bean("users")
  public UserDetailsService users() {
    UserDetails user = User.builder()
        .username("user")
        .password("{bcrypt}$2a$10$1.NSMxlOyMgJHxOi8CWwxuU83G0/HItXxRoBO4QWZMTDp0tzPbCf.")
        .roles("USER")
//        roles 和 authorities 不能并存
//        .authorities(new String[]{"system:user:query", "system:user:edit", "system:user:delete"})
        .build();
    UserDetails admin = User.builder()
        .username("admin")
        .password("{bcrypt}$2a$10$1.NSMxlOyMgJHxOi8CWwxuU83G0/HItXxRoBO4QWZMTDp0tzPbCf.")
//        .roles("USER", "ADMIN")
        .roles("ADMIN")
//        .authorities("system:user:create")
        .build();
    return new InMemoryUserDetailsManager(user, admin);
  }

  /**
   * 角色繼承:
   * 讓Admin角色擁有User的角色的權限
   * @return
   */
  @Bean
  public RoleHierarchy roleHierarchy() {
    RoleHierarchyImpl result = new RoleHierarchyImpl();
    result.setHierarchy("ROLE_ADMIN > ROLE_USER");
    return result;
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(users());
  }

  @Override
  public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/js/**", "/css/**", "/images/**");
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    // 自定義異常處理
    http.exceptionHandling()
        .authenticationEntryPoint(authenticationEntryPoint)
        .accessDeniedHandler(accessDeniedHandler)

        // 權限
        .and()
        .authorizeRequests()
        // 一個是必須待身份信息但是不校驗權限。
        .antMatchers("/", "/mock/login").permitAll()
        //只允許匿名訪問
        .antMatchers("/hello").anonymous()
        .anyRequest()
        .authenticated()

        // 表單登錄
//        .and()
//        .formLogin()
//        .successHandler(authenticationSuccessHandler)
//        .failureHandler(authenticationFailureHandler)
//        .loginProcessingUrl("/login")
//        .permitAll()

        // 注銷
        .and()
        .logout()
        .logoutUrl("/logout")
        .logoutSuccessHandler(logoutSuccessHandler)
        .permitAll()

        // 關閉csrf 會在頁面中生成一個csrf_token
        .and()
        .csrf()
        .disable()

        // 基于token,所以不需要session
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
// 添加我們的JWT過濾器
    .and()
    .addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class)
    ;
  }

  @Bean
  public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
    return new JwtAuthenticationTokenFilter();
  }

  @Bean
  @Override
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }

  @Bean
  public JwtTokenUtil jwtTokenUtil() {
    return new JwtTokenUtil();
  }
}

創建JWT過濾器 繼承 OncePerRequestFilter

這里直接用的macro大佬 mall商城里的例子

package top.ryzeyang.demo.common.filter;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import top.ryzeyang.demo.utils.JwtTokenUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT登錄授權過濾器
 *
 * @author macro
 * @date 2018/4/26
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
  @Qualifier("users")
  @Autowired
  private UserDetailsService userDetailsService;
  @Autowired
  private JwtTokenUtil jwtTokenUtil;
  @Value("${jwt.tokenHeader}")
  private String tokenHeader;
  @Value("${jwt.tokenHead}")
  private String tokenHead;
  @Override
  protected void doFilterInternal(HttpServletRequest request,
                  HttpServletResponse response,
                  FilterChain chain) throws ServletException, IOException {
    String authHeader = request.getHeader(this.tokenHeader);
    if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
      String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
      String username = jwtTokenUtil.getUserNameFromToken(authToken);
      log.info("checking username:{}", username);
      if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
        if (jwtTokenUtil.validateToken(authToken, userDetails)) {
          UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
          authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
          log.info("authenticated user:{}", username);
          SecurityContextHolder.getContext().setAuthentication(authentication);
        }
      }
    }
    chain.doFilter(request, response);
  }
}

自定義handler

這里主要介紹兩個hanler,一個權限不足,一個驗證失敗的

權限不足 實現 AccessDeniedHandler

package top.ryzeyang.demo.common.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import top.ryzeyang.demo.common.api.CommonResult;
import top.ryzeyang.demo.common.api.ResultEnum;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@Component
public class MyAccessDeineHandler implements AccessDeniedHandler {
  @Override
  public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
    httpServletResponse.setContentType("application/json;charset=utf-8");
    PrintWriter writer = httpServletResponse.getWriter();
    writer.write(new ObjectMapper().writeValueAsString(new CommonResult<>(ResultEnum.ACCESS_ERROR, e.getMessage())));
    writer.flush();
    writer.close();
  }
}

認證失敗 實現 AuthenticationEntryPoint

如賬號密碼錯誤等驗證不通過時

package top.ryzeyang.demo.common.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import top.ryzeyang.demo.common.api.CommonResult;
import top.ryzeyang.demo.common.api.ResultEnum;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
  @Override
  public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
    httpServletResponse.setContentType("application/json;charset=utf-8");
    PrintWriter writer = httpServletResponse.getWriter();
//     認證失敗
    writer.write(new ObjectMapper().writeValueAsString(new CommonResult<>(ResultEnum.AUTHENTICATION_ERROR, e.getMessage())));
    writer.flush();
    writer.close();
  }
}

JWT工具類

這里直接用的macro大佬 mall商城里的例子

稍微改了一點,因為 JDK11 用的 jjwt 版本不一樣 ,語法也有些不同

pom 文件中引入 jjwt

<dependency>
  <groupId>io.jsonwebtoken</groupId>
  <artifactId>jjwt-api</artifactId>
  <version>0.11.2</version>
</dependency>
<dependency>
  <groupId>io.jsonwebtoken</groupId>
  <artifactId>jjwt-impl</artifactId>
  <version>0.11.2</version>
  <scope>runtime</scope>
</dependency>
<dependency>
  <groupId>io.jsonwebtoken</groupId>
  <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
  <version>0.11.2</version>
  <scope>runtime</scope>
</dependency>

JwtTokenUtil

package top.ryzeyang.demo.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JwtToken生成的工具類
 * JWT token的格式:header.payload.signature
 * header的格式(算法、token的類型):
 * {"alg": "HS512","typ": "JWT"}
 * payload的格式(用戶名、創建時間、生成時間):
 * {"sub":"wang","created":1489079981393,"exp":1489684781}
 * signature的生成算法:
 * HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
 *
 * @author macro
 * @date 2018/4/26
 */
@Slf4j
public class JwtTokenUtil {
  private static final String CLAIM_KEY_USERNAME = "sub";
  private static final String CLAIM_KEY_CREATED = "created";

  @Value("${jwt.secret}")
  private String secret;

  @Value("${jwt.expiration}")
  private Long expiration;

  @Value("${jwt.tokenHead}")
  private String tokenHead;

  private SecretKey getSecretKey() {
    byte[] encodeKey = Decoders.BASE64.decode(secret);
    return Keys.hmacShaKeyFor(encodeKey);
  }

  /**
   * 根據負責生成JWT的token
   */
  private String generateToken(Map<String, Object> claims) {
    SecretKey secretKey = getSecretKey();
    return Jwts.builder()
        .setClaims(claims)
        .setExpiration(generateExpirationDate())
        .signWith(secretKey)
        .compact();
  }

  /**
   * 測試生成的token
   * @param claims
   * @return
   */
  public String generateToken2(Map<String, Object> claims) {
    SecretKey secretKey = getSecretKey();
    return Jwts.builder()
        .setClaims(claims)
        .setIssuer("Java4ye")
        .setExpiration(new Date(System.currentTimeMillis() + 1 * 1000))
        .signWith(secretKey)
        .compact();
  }

  /**
   * 從token中獲取JWT中的負載
   */
  private Claims getClaimsFromToken(String token) {
    SecretKey secretKey = getSecretKey();
    Claims claims = null;
    try {
      claims = Jwts.parserBuilder()
          .setSigningKey(secretKey)
          .build()
          .parseClaimsJws(token)
          .getBody();
    } catch (Exception e) {
      log.info("JWT格式驗證失敗:{}", token);
    }
    return claims;
  }

  /**
   * 生成token的過期時間
   */
  private Date generateExpirationDate() {
    return new Date(System.currentTimeMillis() + expiration * 1000);
  }

  /**
   * 從token中獲取登錄用戶名
   */
  public String getUserNameFromToken(String token) {
    String username;
    try {
      Claims claims = getClaimsFromToken(token);
      username = claims.getSubject();
    } catch (Exception e) {
      username = null;
    }
    return username;
  }

  /**
   * 驗證token是否還有效
   *
   * @param token    客戶端傳入的token
   * @param userDetails 從數據庫中查詢出來的用戶信息
   */
  public boolean validateToken(String token, UserDetails userDetails) {
    String username = getUserNameFromToken(token);
    return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
  }

  /**
   * 判斷token是否已經失效
   */
  private boolean isTokenExpired(String token) {
    Date expiredDate = getExpiredDateFromToken(token);
    return expiredDate.before(new Date());
  }

  /**
   * 從token中獲取過期時間
   */
  private Date getExpiredDateFromToken(String token) {
    Claims claims = getClaimsFromToken(token);
    return claims.getExpiration();
  }

  /**
   * 根據用戶信息生成token
   */
  public String generateToken(UserDetails userDetails) {
    Map<String, Object> claims = new HashMap<>();
    claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
    claims.put(CLAIM_KEY_CREATED, new Date());
    return generateToken(claims);
  }

  /**
   * 當原來的token沒過期時是可以刷新的
   *
   * @param oldToken 帶tokenHead的token
   */
  public String refreshHeadToken(String oldToken) {
    if (StrUtil.isEmpty(oldToken)) {
      return null;
    }
    String token = oldToken.substring(tokenHead.length());
    if (StrUtil.isEmpty(token)) {
      return null;
    }
    //token校驗不通過
    Claims claims = getClaimsFromToken(token);
    if (claims == null) {
      return null;
    }
    //如果token已經過期,不支持刷新
    if (isTokenExpired(token)) {
      return null;
    }
    //如果token在30分鐘之內剛刷新過,返回原token
    if (tokenRefreshJustBefore(token, 30 * 60)) {
      return token;
    } else {
      claims.put(CLAIM_KEY_CREATED, new Date());
      return generateToken(claims);
    }
  }

  /**
   * 判斷token在指定時間內是否剛剛刷新過
   *
   * @param token 原token
   * @param time 指定時間(秒)
   */
  private boolean tokenRefreshJustBefore(String token, int time) {
    Claims claims = getClaimsFromToken(token);
    Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
    Date refreshDate = new Date();
    //刷新時間在創建時間的指定時間內
    if (refreshDate.after(created) && refreshDate.before(DateUtil.offsetSecond(created, time))) {
      return true;
    }
    return false;
  }
}

配置文件 application.yml

這里的 secret 可以用該方法生成

@Test
  void generateKey() {
    /**
     * SECRET 是簽名密鑰,只生成一次即可,生成方法:
     * Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
     * String secretString = Encoders.BASE64.encode(key.getEncoded()); # 本文使用 BASE64 編碼
     * */
    Key key = Keys.secretKeyFor(SignatureAlgorithm.HS512);
    String secretString = Encoders.BASE64.encode(key.getEncoded());
    System.out.println(secretString);
//    Blk1X8JlN4XH4s+Kuc0YUFXv+feyTgVUMycSiKbiL0YhRddy872mCNZBGZIb57Jn2V1RtaFXIxs8TvNPsnG//g==
  }
jwt:
 tokenHeader: Authorization
 secret: Blk1X8JlN4XH4s+Kuc0YUFXv+feyTgVUMycSiKbiL0YhRddy872mCNZBGZIb57Jn2V1RtaFXIxs8TvNPsnG//g==
 expiration: 604800
 tokenHead: 'Bearer '

server:
 servlet:
 context-path: /api

Controller

AuthController

package top.ryzeyang.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;
import top.ryzeyang.demo.common.api.CommonResult;
import top.ryzeyang.demo.model.dto.UserDTO;
import top.ryzeyang.demo.utils.CommonResultUtil;
import top.ryzeyang.demo.utils.JwtTokenUtil;

import java.util.Collection;

@RestController
@ResponseBody
@RequestMapping("/mock")
public class AuthController {
  @Autowired
  private JwtTokenUtil jwtTokenUtil;
  @Qualifier("users")
  @Autowired
  private UserDetailsService userDetailsService;
  @Autowired
  AuthenticationManager authenticationManager;

  @GetMapping("/userinfo")
  public CommonResult<Collection<? extends GrantedAuthority>> getUserInfo(){
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    return CommonResultUtil.success(authorities);
  }

  /**
   * 模擬登陸
   */
  @PostMapping("/login")
  public CommonResult<String> login(@RequestBody UserDTO userDTO){
    String username = userDTO.getUsername();
    String password = userDTO.getPassword();
    UsernamePasswordAuthenticationToken token
        = new UsernamePasswordAuthenticationToken(username, password);
    Authentication authenticate = authenticationManager.authenticate(token);
    SecurityContextHolder.getContext().setAuthentication(authenticate);
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    String t = jwtTokenUtil.generateToken(userDetails);
    return CommonResultUtil.success(t);
  }
}

HelloController

package top.ryzeyang.demo.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class HelloController {

  @GetMapping("/hello")
  public String hello() {
    return "hello";
  }

  @GetMapping("/hello/anonymous")
  public String hello2() {
    return "anonymous";
  }

  @PreAuthorize("hasRole('ADMIN')")
  @GetMapping("/hello/admin")
  public String helloAdmin() {
    return "hello Admin";
  }

  @PreAuthorize("hasRole('USER')")
  @GetMapping("/hello/user")
  public String helloUser() {
    return "hello user";
  }

  @PreAuthorize("hasAnyAuthority('system:user:query')")
  @GetMapping("/hello/user2")
  public String helloUser2() {
    return "hello user2";
  }
}

關于怎么在SpringSecurity中利用JWT實現一個前后端分離功能就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

房山区| 鄂伦春自治旗| 丰宁| 万年县| 惠安县| 孟连| 鄢陵县| 大田县| 积石山| 灵石县| 吐鲁番市| 阳朔县| 米林县| 饶河县| 榕江县| 延川县| 铁力市| 天峨县| 康乐县| 鄄城县| 宜章县| 兴隆县| 安陆市| 怀来县| 平定县| 齐河县| 台北县| 怀宁县| 平顶山市| 武陟县| 苍南县| 光泽县| 汾西县| 星子县| 兴宁市| 江山市| 历史| 平乐县| 辽阳市| 汕头市| 抚远县|