1. 程式人生 > 其它 >輕鬆上手SpringBoot+SpringSecurity+JWT實RESTfulAPI許可權控制實戰

輕鬆上手SpringBoot+SpringSecurity+JWT實RESTfulAPI許可權控制實戰

前言

我們知道在專案開發中,後臺開發許可權認證是非常重要的,springboot 中常用熟悉的許可權認證框架有,shiro,還有就是springboot 全家桶的 security當然他們各有各的好處,但是我比較喜歡springboot自帶的許可權認證框架

<!--springboot 許可權認證-->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-security</artifactId>
      </dependency>

與springboot天然整合,功能強大

快速上手

主要實現 Spring Security 的安全認證,結合 RESTful API 的風格,使用無狀態的環境。

主要實現是通過請求的 URL ,通過過濾器來做不同的授權策略操作,為該請求提供某個認證的方法,然後進行認證,授權成功返回授權例項資訊,供服務呼叫。

基於Token的身份驗證的過程如下:

使用者通過使用者名稱和密碼傳送請求。
程式驗證。
程式返回一個簽名的token 給客戶端。
客戶端儲存token,並且每次用於每次傳送請求。
服務端驗證token並返回資料。
每一次請求都需要token,所以每次請求都會去驗證使用者身份,所以這裡必須要使用快取,

流程圖

JWT JSON Web Token 驗證流程圖

新增Spring Security和JWT依賴項

       <!--springboot 許可權認證-->
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-security</artifactId>
          </dependency>
         <!--jwt 認證-->
         <dependency>
             <groupId>io.jsonwebtoken</groupId>
             <artifactId>jjwt</artifactId>
         </dependency>

生成JWT toke

因為要生成JWT toke 所以就寫了一個工具類JwtTokenUtil

package cn.soboys.kmall.security.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * @author kenx
 * @version 1.0
 * @date 2021/8/5 22:28
 * @webSite https://www.soboys.cn/
 */
@Component
public class JwtTokenUtil implements Serializable {

    private static final long serialVersionUID = -2550185165626007488L;

    public static final long JWT_TOKEN_VALIDITY = 7*24*60*60;

    private String secret="TcUF7CC8T3txmfQ38pYsQ3KY";

    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }


    public String generateToken(String username) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, username);
    }

    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = getUsernameFromToken(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }


    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }


    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    private String doGenerateToken(Map<String, Object> claims, String subject) {
        return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY*1000)).signWith(SignatureAlgorithm.HS512, secret).compact();
    }
}

注入資料來源

這裡我們使用資料庫作為許可權控制資料儲存,所以就要注入資料來源,進行許可權認證
Spring Security提供了 UserDetailsService介面 用於使用者身份認證,和UserDetails實體類,用於儲存使用者資訊,(使用者憑證,許可權等)

看原始碼

package org.springframework.security.core.userdetails;

public interface UserDetailsService {
    UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException;
}
package org.springframework.security.core.userdetails;
public interface UserDetails extends Serializable {
    Collection<? extends GrantedAuthority> getAuthorities();

    String getPassword();

    String getUsername();

    boolean isAccountNonExpired();

    boolean isAccountNonLocked();

    boolean isCredentialsNonExpired();

    boolean isEnabled();
}

所以我們分為兩步走:

  1. 自己的User實體類繼承Spring SecurityUserDetails 儲存相關許可權資訊
package cn.soboys.kmall.security.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 使用者表
 * </p>
 *
 * @author kenx
 * @since 2021-08-06
 */
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_user")
public class User implements Serializable, UserDetails {

    private static final long serialVersionUID = 1L;

    /**
     * 使用者ID
     */
    @TableId(value = "USER_ID", type = IdType.AUTO)
    private Long userId;

    /**
     * 使用者名稱
     */
    @TableField("USERNAME")
    private String username;

    /**
     * 密碼
     */
    @TableField("PASSWORD")
    private String password;

    /**
     * 部門ID
     */
    @TableField("DEPT_ID")
    private Long deptId;

    /**
     * 郵箱
     */
    @TableField("EMAIL")
    private String email;

    /**
     * 聯絡電話
     */
    @TableField("MOBILE")
    private String mobile;

    /**
     * 狀態 0鎖定 1有效
     */
    @TableField("STATUS")
    private String status;

    /**
     * 建立時間
     */
    @TableField("CREATE_TIME")
    private Date createTime;

    /**
     * 修改時間
     */
    @TableField("MODIFY_TIME")
    private Date modifyTime;

    /**
     * 最近訪問時間
     */
    @TableField("LAST_LOGIN_TIME")
    private Date lastLoginTime;

    /**
     * 性別 0男 1女 2保密
     */
    @TableField("SSEX")
    private String ssex;

    /**
     * 是否開啟tab,0關閉 1開啟
     */
    @TableField("IS_TAB")
    private String isTab;

    /**
     * 主題
     */
    @TableField("THEME")
    private String theme;

    /**
     * 頭像
     */
    @TableField("AVATAR")
    private String avatar;

    /**
     * 描述
     */
    @TableField("DESCRIPTION")
    private String description;

    @TableField(exist = false)
    private List<Role> roles;


    @TableField(exist = false)
    private Set<String> perms;

    /**
     * 使用者許可權
     *
     * @return
     */
    /*@Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> auths = new ArrayList<>();
        List<Role> roles = this.getRoles();
        for (Role role : roles) {
            auths.add(new SimpleGrantedAuthority(role.getRolePerms()));
        }
        return auths;
    }*/
    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> auths = new ArrayList<>();
        Set<String> perms = this.getPerms();
        for (String perm : perms) {
            //這裡perms值如果為空或空字元會報錯
            auths.add(new SimpleGrantedAuthority(perm));
        }
        return auths;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isEnabled() {
        return true;
    }
}

注意這裡有一個問題 登入使用者時,總提示 User account is locked

是因為使用者實體類實現UserDetails這個介面時,我預設把所有抽象方法給自動實現了,而自動生成下面這四個方法,預設返回false,

    @Override
    public boolean isAccountNonExpired() {
        return false;
    }
 
    @Override
    public boolean isAccountNonLocked() {
        return false;
    }
 
    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }
 
    @Override
    public boolean isEnabled() {
        return false;
    }

問題原因就在這裡,只要把它們的返回值改成true就行。

UserDetails 中幾個欄位的解釋:

//返回驗證使用者密碼,無法返回則NULL

String getPassword();
String getUsername();

賬戶是否過期,過期無法驗證

boolean isAccountNonExpired();

指定使用者是否被鎖定或者解鎖,鎖定的使用者無法進行身份驗證

boolean isAccountNonLocked();

指示是否已過期的使用者的憑據(密碼),過期的憑據防止認證

boolean isCredentialsNonExpired();

是否被禁用,禁用的使用者不能身份驗證

boolean isEnabled();
  1. 實現介面中loadUserByUsername方法注入資料驗證就可以了

自己IUserService使用者介面類繼承Spring Security提供了 UserDetailsService介面

public interface IUserService  extends IService<User>, UserDetailsService {

    User getUserByUsername(String username);

   /* *//**
     * 獲取使用者所有許可權
     *
     * @param username
     * @return
     *//*
    Set<String> getUserPerms(String username);*/

}

並且加以實現

@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private final RoleMapper roleMapper;

    @Override
    public User getUserByUsername(String username) {
        return this.baseMapper.selectOne(new QueryWrapper<User>().lambda()
                .eq(User::getUsername, username));
    }


    /**
     * 對使用者提供的使用者詳細資訊進行身份驗證時
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = this.getUserByUsername(username);

        if (StrUtil.isBlankIfStr(user)) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }

        //獲取使用者角色資訊
        List<Role> roles = roleMapper.findUserRolePermsByUserName(username);
        user.setRoles(roles);

        List<String> permList = this.baseMapper.findUserPerms(username);

        //java8 stream 便利
        Set<String> perms = permList.stream().filter(o->StrUtil.isNotBlank(o)).collect(Collectors.toSet());
        user.setPerms(perms);

        //用於新增使用者的許可權。只要把使用者許可權新增到authorities 就萬事大吉。
        // List<SimpleGrantedAuthority> authorities = new ArrayList<>();


        //用於新增使用者的許可權。只要把使用者許可權新增到authorities 就萬事大吉。
        /*for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getRolePerms()));
            log.info("loadUserByUsername: " + user);
        }*/
        //user.setAuthorities(authorities);//用於登入時 @AuthenticationPrincipal 標籤取值
        return user;
    }


}

自己實現loadUserByUsername從資料庫中驗證使用者名稱密碼,獲取使用者角色許可權資訊

攔截器配置

Spring Security的AuthenticationEntryPoint類,它拒絕每個未經身份驗證的請求併發送錯誤程式碼401

package cn.soboys.kmall.security.config;

import cn.soboys.kmall.common.ret.Result;
import cn.soboys.kmall.common.ret.ResultCode;
import cn.soboys.kmall.common.ret.ResultResponse;
import cn.soboys.kmall.common.utils.ResponseUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

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

/**
 * @author kenx
 * @version 1.0
 * @date 2021/8/5 22:30
 * @webSite https://www.soboys.cn/
 * 此類繼承Spring Security的AuthenticationEntryPoint類,
 * 並重寫其commence。它拒絕每個未經身份驗證的請求併發送錯誤程式碼401。
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    /**
     * 此類繼承Spring Security的AuthenticationEntryPoint類,並重寫其commence。
     * 它拒絕每個未經身份驗證的請求併發送錯誤程式碼401
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        Result result = ResultResponse.failure(ResultCode.UNAUTHORIZED, "請先登入");
        ResponseUtil.responseJson(httpServletResponse, result);
    }
}

JwtRequestFilter 任何請求都會執行此類檢查請求是否具有有效的JWT令牌。如果它具有有效的JWT令牌,則它將在上下文中設定Authentication,以指定當前使用者已通過身份驗證。

package cn.soboys.kmall.security.config;

import cn.soboys.kmall.common.utils.ConstantFiledUtil;
import cn.soboys.kmall.security.service.IUserService;
import cn.soboys.kmall.security.utils.JwtTokenUtil;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

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

/**
 * @author kenx
 * @version 1.0
 * @date 2021/8/5 22:27
 * @webSite https://www.soboys.cn/
 * 任何請求都會執行此類
 * 檢查請求是否具有有效的JWT令牌。如果它具有有效的JWT令牌,
 * 則它將在上下文中設定Authentication,以指定當前使用者已通過身份驗證。
 */
@Component
@Slf4j
public class JwtRequestFilter extends OncePerRequestFilter {

    //使用者資料源
    private IUserService userService;
    //生成jwt 的token
    private  JwtTokenUtil jwtTokenUtil;

    public JwtRequestFilter(IUserService userService,JwtTokenUtil jwtTokenUtil) {
        this.userService = userService;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        final String requestTokenHeader = request.getHeader(ConstantFiledUtil.AUTHORIZATION_TOKEN);

        String username = null;
        String jwtToken = null;
        // JWT Token is in the form "Bearer token". Remove Bearer word and get only the Token
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            try {
                username = jwtTokenUtil.getUsernameFromToken(jwtToken);
            } catch (IllegalArgumentException e) {
                log.error("Unable to get JWT Token");
            } catch (ExpiredJwtException e) {
                log.error("JWT Token has expired");
            }
        } else {
            //logger.warn("JWT Token does not begin with Bearer String");
        }

        //Once we get the token validate it.
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            UserDetails userDetails = this.userService.loadUserByUsername(username);

            // if token is valid configure Spring Security to manually set authentication
            if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {

                //儲存使用者資訊和許可權資訊
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // After setting the Authentication in the context, we specify
                // that the current user is authenticated. So it passes the Spring Security Configurations successfully.
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        filterChain.doFilter(request, response);
    }
}

配置Spring Security 配置類SecurityConfig

  1. 自定義Spring Security的時候我們需要繼承自WebSecurityConfigurerAdapter來完成,相關配置重寫對應 方法

  2. 此處使用了 BCryptPasswordEncoder 密碼加密

  3. 通過重寫configure方法新增我們自定義的認證方式。

package cn.soboys.kmall.security.config;


import cn.soboys.kmall.security.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.Set;

/**
 * @author kenx
 * @version 1.0
 * @date 2021/8/6 17:27
 * @webSite https://www.soboys.cn/
 */
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) // 控制權限註解
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    private IUserService userService;
    private JwtRequestFilter jwtRequestFilter;


    public SecurityConfig(JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint,
                          IUserService userService,
                          JwtRequestFilter jwtRequestFilter) {
        this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint;
        this.userService = userService;
        this.jwtRequestFilter = jwtRequestFilter;
    }


    /**
     * 1)HttpSecurity支援cors。
     * 2)預設會啟用CRSF,此處因為沒有使用thymeleaf模板(會自動注入_csrf引數),
     * 要先禁用csrf,否則登入時需要_csrf引數,而導致登入失敗。
     * 3)antMatchers:匹配 "/" 路徑,不需要許可權即可訪問,匹配 "/user" 及其以下所有路徑,
     * 都需要 "USER" 許可權
     * 4)配置登入地址和退出地址
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // We don't need CSRF for this example
        http.csrf().disable()
                // dont authenticate this particular request
                .authorizeRequests().antMatchers("/", "/*.html", "/favicon.ico", "/css/**", "/js/**", "/fonts/**", "/layui/**", "/img/**",
                "/v3/api-docs/**", "/swagger-resources/**", "/webjars/**", "/pages/**", "/druid/**",
                "/statics/**", "/login", "/register").permitAll().
                // all other requests need to be authenticated
                        anyRequest().authenticated().and().
                // make sure we use stateless session; session won't be used to
                // store user's state.
                //覆蓋預設登入
                        exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                // 基於token,所以不需要session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);


        // Add a filter to validate the tokens with every request
        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }


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

    /**
     * 密碼校驗
     *
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // configure AuthenticationManager so that it knows from where to load
        // user for matching credentials
        // Use BCryptPasswordEncoder
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }

    /**
     * 密碼加密驗證
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


}

具體應用

package cn.soboys.kmall.security.controller;

import cn.hutool.core.util.StrUtil;
import cn.soboys.kmall.common.exception.BusinessException;
import cn.soboys.kmall.common.ret.ResponseResult;
import cn.soboys.kmall.common.ret.Result;
import cn.soboys.kmall.common.ret.ResultResponse;
import cn.soboys.kmall.security.entity.User;
import cn.soboys.kmall.security.service.IUserService;
import cn.soboys.kmall.security.utils.EncryptPwdUtil;
import cn.soboys.kmall.security.utils.JwtTokenUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.util.Date;
import java.util.Objects;

/**
 * @author kenx
 * @version 1.0
 * @date 2021/8/6 12:30
 * @webSite https://www.soboys.cn/
 */
@RestController
@ResponseResult
@Validated
@RequiredArgsConstructor
@Api(tags = "登入介面")
public class LoginController {
    private final IUserService userService;
    //認證管理,認證使用者省份
    private final AuthenticationManager authenticationManager;
    private final JwtTokenUtil jwtTokenUtil;
    //自己資料來源
    private final UserDetailsService jwtInMemoryUserDetailsService;




    @PostMapping("/login")
    @ApiOperation("使用者登入")
    @SneakyThrows
    public Result login(@NotBlank @RequestParam String username,
                        @NotBlank @RequestParam String password) {


        Authentication authentication= this.authenticate(username, password);

        String user = authentication.getName();

        final String token = jwtTokenUtil.generateToken(user);
        //更新使用者最後登入時間
        User u = new User();
        u.setLastLoginTime(new Date());
        userService.update(u, new UpdateWrapper<User>().lambda().eq(User::getUsername, username));
        return ResultResponse.success("Bearer " + token);
    }

    @PostMapping("/register")
    @ApiOperation("使用者註冊")
    public Result register(@NotEmpty @RequestParam String username, @NotEmpty @RequestParam String password) {
        User user = userService.getUserByUsername(username);

        if (!StrUtil.isBlankIfStr(user)) {
            throw new BusinessException("使用者已存在");
        }
        User u = new User();
        u.setPassword(EncryptPwdUtil.encryptPassword(password));
        u.setUsername(username);
        u.setCreateTime(new Date());
        u.setModifyTime(new Date());
        u.setStatus("1");
        userService.save(u);
        return ResultResponse.success();

    }


    private Authentication authenticate(String username, String password) throws Exception {
        Authentication authentication = null;
        try {
            //security 認證使用者身份
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (DisabledException e) {
            throw new BusinessException("使用者不存");
        } catch (BadCredentialsException e) {
            throw new BusinessException("使用者名稱密碼錯誤");
        }

        return authentication;
    }
}

深入瞭解

Spring Security 配置講解

  1. @EnableWebSecurity 開啟許可權認證
  2. @EnableGlobalMethodSecurity(prePostEnabled = true) 開啟許可權註解認證
  3. configure 配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // We don't need CSRF for this example
        http.csrf().disable()
                // dont authenticate this particular request
                .authorizeRequests().antMatchers("/", "/*.html", "/favicon.ico", "/css/**", "/js/**", "/fonts/**", "/layui/**", "/img/**",
                "/v3/api-docs/**", "/swagger-resources/**", "/webjars/**", "/pages/**", "/druid/**",
                "/statics/**", "/login", "/register").permitAll().
                // all other requests need to be authenticated
                        anyRequest().authenticated().and().
                // make sure we use stateless session; session won't be used to
                // store user's state.
                //覆蓋預設登入
                        exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                // 基於token,所以不需要session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);


        // Add a filter to validate the tokens with every request
        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }

參考

  1. Spring Security 許可權認證
  2. springSecurity 之 http Basic認證
  3. 輕鬆上手SpringBoot Security + JWT Hello World示例