1. 程式人生 > 資訊 >育碧:首部中國原創漫畫 《刺客信條:王朝》數字版全網閱讀量突破 10 億

育碧:首部中國原創漫畫 《刺客信條:王朝》數字版全網閱讀量突破 10 億

  • 基於Spring security 使用JWT實現登入

  • 專案依賴pom

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
  <version>2.5.6</version>
</dependency>
  • 實現核心程式碼

  • 配置類

package ***.***.framework.config;

import
org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpMethod; 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.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.logout.LogoutFilter; import org.springframework.web.filter.CorsFilter; import ***.***.framework.security.filter.JwtAuthenticationTokenFilter; import ***.***.framework.security.handle.AuthenticationEntryPointImpl; import ***.***.framework.security.handle.LogoutSuccessHandlerImpl; import javax.annotation.Resource; /** * spring security配置 * * @author*/ @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { /** * 自定義使用者認證邏輯 */ @Resource(name = "userDetailsServiceImpl") private UserDetailsService userDetailsService; /** * 認證失敗處理類 */ @Autowired private AuthenticationEntryPointImpl unauthorizedHandler; /** * 退出處理類 */ @Autowired private LogoutSuccessHandlerImpl logoutSuccessHandler; /** * token認證過濾器 */ @Autowired private JwtAuthenticationTokenFilter authenticationTokenFilter; /** * 跨域過濾器 */ @Autowired private CorsFilter corsFilter; /** * 解決 無法直接注入 AuthenticationManager * * @return * @throws Exception */ @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } /** * anyRequest | 匹配所有請求路徑 * access | SpringEl表示式結果為true時可以訪問 * anonymous | 匿名可以訪問 * denyAll | 使用者不能訪問 * fullyAuthenticated | 使用者完全認證可以訪問(非remember-me下自動登入) * hasAnyAuthority | 如果有引數,引數表示許可權,則其中任何一個許可權可以訪問 * hasAnyRole | 如果有引數,引數表示角色,則其中任何一個角色可以訪問 * hasAuthority | 如果有引數,引數表示許可權,則其許可權可以訪問 * hasIpAddress | 如果有引數,引數表示IP地址,如果使用者IP和引數匹配,則可以訪問 * hasRole | 如果有引數,引數表示角色,則其角色可以訪問 * permitAll | 使用者可以任意訪問 * rememberMe | 允許通過remember-me登入的使用者訪問 * authenticated | 使用者登入後可訪問 */ @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity // CSRF禁用,因為不使用session .csrf().disable() // 認證失敗處理類 .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() // 基於token,所以不需要session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() // 過濾請求 .authorizeRequests() // 對於登入login 註冊register 驗證碼captchaImage 允許匿名訪問 .antMatchers("/login", "/register", "/captchaImage") .anonymous() .antMatchers( HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**" ).permitAll() .antMatchers("/swagger-ui.html").anonymous() .antMatchers("/swagger-resources/**").anonymous() .antMatchers("/webjars/**").anonymous() .antMatchers("/*/api-docs").anonymous() .antMatchers("/druid/**").anonymous() .antMatchers("/webSocket/**").permitAll() // 除上面外的所有請求全部需要鑑權認證 .anyRequest().authenticated() .and() .headers().frameOptions().disable(); httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler); // 新增JWT filter httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); // 新增CORS filter httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class); httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class); } /** * 強雜湊雜湊加密實現 */ @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } /** * 身份認證介面 */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); } }
  • 使用者驗證處理類

package ***.***framework.web.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import ***.***common.core.domain.entity.SysUser;
import ***.***common.core.domain.model.LoginUser;
import ***.***common.enums.UserStatus;
import ***.***common.exception.ServiceException;
import ***.***common.utils.StringUtils;
import ***.***system.service.ISysUserService;

/**
 * ****************************************
 * 使用者驗證處理類
 * ****************************************
 *
 * @author xielei
 * @title: UserDetailsServiceImpl
 * @projectName
 * @date 2022/1/17 10:17
 */
@Service("userDetailsServiceImpl")
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查詢根據使用者名稱查詢使用者資訊
        SysUser user = userService.selectUserByUserName(username);
        //使用者資訊驗證
        if (StringUtils.isNull(user)) {
            log.info("登入使用者:{} 不存在.", username);
            throw new ServiceException(String.format("登入使用者:%s 不存在", username));
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登入使用者:{} 已被刪除.", username);
            throw new ServiceException(String.format("對不起,您的賬號:%s 已被刪除", username));
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登入使用者:{} 已被停用.", username);
            throw new ServiceException(String.format("對不起,您的賬號:%s 已停用", username));
        }

        return createLoginUser(user);
    }

    /**
     * 建立使用者登入資訊
     * @param user 引數
     * @return 結果
     */
    public UserDetails createLoginUser(SysUser user) {
        //實現UserDetails自定義的使用者資訊登入類,構建使用者需要用到的基本資訊屬性 建議此處構建的使用者資訊進行快取
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }
}
  • 認證失敗處理類
package ***.***.framework.security.handle;

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

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import ***.***.common.constant.HttpStatus;
import ***.***.common.core.domain.AjaxResult;
import ***.***.common.utils.ServletUtils;
import ***.***.common.utils.StringUtils;


/**
 * ****************************************
 * 認證失敗處理類 返回未授權
 * ****************************************
 *
 * @author xielei
 * @title: AuthenticationEntryPointImpl
 * @date 2022/1/17 10:17
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException {
        int code = HttpStatus.UNAUTHORIZED;
        String msg = StringUtils.format("請求訪問:{},認證失敗,無法訪問系統資源", request.getRequestURI());
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
    }
}
  • 自定義退出處理類

package ***.***.framework.security.handle;

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

import ***.***.framework.manager.AsyncManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import com.alibaba.fastjson.JSON;
import ***.***.common.constant.Constants;
import ***.***.common.constant.HttpStatus;
import ***.***.common.core.domain.AjaxResult;
import ***.***.common.core.domain.model.LoginUser;
import ***.***.common.utils.ServletUtils;
import ***.***.common.utils.StringUtils;
import ***.***.framework.manager.factory.AsyncFactory;
import ***.***.framework.web.service.TokenService;

/**
 * ****************************************
 * 自定義退出處理類
 * ****************************************
 * 
 * @author xielei
 * @title: LogoutSuccessHandlerImpl
 * @date 2022/1/17 10:17
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Autowired
    private TokenService tokenService;

    /**
     * 退出處理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        //獲取使用者資訊
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            String userName = loginUser.getUsername();
            // 刪除使用者快取記錄
            tokenService.delLoginUser(loginUser.getToken());
            // 記錄使用者退出日誌
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
        }
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.SUCCESS, "退出成功")));
    }
}
  • 自定義token認證過濾器

package ***.***.framework.security.filter;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import ***.***.common.core.domain.model.LoginUser;
import ***.***.common.utils.SecurityUtils;
import ***.***.common.utils.StringUtils;
import ***.***.framework.web.service.TokenService;


/**
 * ****************************************
 * token過濾器 驗證token有效性
 * ****************************************
 *
 * @author xielei
 * @title: UserDetailsServiceImpl
 * @date 2022/1/17 10:17
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        //放行websocket相關請求
        if (request.getRequestURI().contains("/webSocket")) {
            chain.doFilter(request, response);
            return;
        }
        //獲取使用者資訊
        LoginUser loginUser = tokenService.getLoginUser(request);

        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            //設定認證使用者的token資訊
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //設定當前使用者資訊
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }
}
    
  • 自定義跨域配置

/**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilter()
    {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 設定訪問源地址
        config.addAllowedOriginPattern("*");
        // 設定訪問源請求頭
        config.addAllowedHeader("*");
        // 設定訪問源請求方法
        config.addAllowedMethod("*");
        // 有效期 1800秒
        config.setMaxAge(1800L);
        // 新增對映路徑,攔截一切請求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }
  • 工具類獲取每次客戶端請求使用者資訊

/**
     * 獲取Authentication
     */
    public static Authentication getAuthentication() {
    //此處設定的值見 token過濾器 驗證token有效性處程式碼 SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        return SecurityContextHolder.getContext().getAuthentication();
    }