精品欧美一区二区三区在线观看 _久久久久国色av免费观看性色_国产精品久久在线观看_亚洲第一综合网站_91精品又粗又猛又爽_小泽玛利亚一区二区免费_91亚洲精品国偷拍自产在线观看 _久久精品视频在线播放_美女精品久久久_欧美日韩国产成人在线

SpringBoot動態權限校驗:從零到一實現高效、優雅的解決方案

開發 前端
LoginFilter.java繼承UsernamePasswordAuthenticationFilter,負責過濾登錄請求并交由登錄認證管理器進行具體的認證。

1、背景

簡單先說一下需求吧,這樣也好讓看的人知道到底適不適合自己。
  • 實現自定義的登錄認證。
  • 登錄成功,生成token并將token 交由redis管理。
  • 登錄后對用戶訪問的接口進行接口級別權限認證。

SpringSecurity提供的注解權限校驗適合的場景是系統中僅有固定的幾個角色,且角色的憑證不可修改(如果修改需要改動代碼)。

@PreAuthorize("hasAuthority('ROLE_TELLER')") 
public Account post(Account account, double amount);

注:ROLE_TELLER是寫死的。

后端系統的訪問請求有以下幾種類型:

  • 登錄、登出(可自定義url)
  • 匿名用戶可訪問的接口(靜態資源,demo示例等)
  • 其他接口(在登錄的前提下,繼續判斷訪問者是否有權限訪問)

2、環境搭建

依賴引入,包括SpringSecurity、Redis、RedisSession需要的依賴:
<!--springSecurity安全框架-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>2.3.4.RELEASE</version>
</dependency>
<!-- 默認通過SESSIONId改為通過請求頭與redis配合驗證session -->
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
    <version>2.3.1.RELEASE</version>
</dependency>
<!--redis支持-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.3.4.RELEASE</version>
</dependency>

注:springBoot版本也是2.3.4.RELEASE,如果有版本對應問題,自行解決。有用到swagger,為了便于測試。

新建springSecurity配置類

繼承自 WebSecurityConfigurerAdapter,過濾匿名用戶可訪問的接口。

WebSecurityConfig作為springSecurity的主配置文件。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    /**
     * Swagger等靜態資源不進行攔截
     */
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(
                "/*.html",
                "/favicon.ico",
                "/**/*.html",
                "/**/*.css",
                "/**/*.js",
                "/error",
                "/webjars/**",
                "/resources/**",
                "/swagger-ui.html",
                "/swagger-resources/**",
                "/v2/api-docs");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //配置一些不需要登錄就可以訪問的接口
                .antMatchers("/demo/**", "/about/**").permitAll()
                //任何尚未匹配的URL只需要用戶進行身份驗證
                .anyRequest().authenticated()
                .and()
                .formLogin()//允許用戶進行基于表單的認證
                .loginPage("/mylogin");
    }

}

注:證明可以訪問靜態資源不會被攔截

自定義登錄認證

springSecurity是基于過濾器進行安全認證的。

我們需要自定義:

  • 登錄過濾器:負責過濾登錄請求,再交由自定義的登錄認證管理器處理。
  • 登錄成功處理類:顧名思義,登錄成功后的一些處理(設置返回信息提示“登錄成功!”,返回數據類型為json)。
  • 登錄失敗處理類:類似登錄成功處理類。ps:登錄成功處理類和失敗處理類有默認的實現可以不自定義。但是建議自定義,因為返回的信息為英文,一般情況不符合要求。
  • 登錄認證管理器:根據過濾器傳過來的登錄參數,進行登錄認證,認證后授權。

新建登錄成功處理類

需要實現 AuthenticationSuccessHandler

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomAuthenticationSuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        //登錄成功返回的認證體,具體格式在后面的登錄認證管理器中
        String responseJson = JackJsonUtil.object2String(ResponseFactory.success(authentication));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("登錄成功!");
        }
        response.getWriter().write(responseJson);
    }
}

新建登錄失敗處理類

實現 AuthenticationFailureHandler

@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomAuthenticationFailureHandler.class);

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        String errorMsg;
        if (StringUtils.isNotBlank(e.getMessage())) {
            errorMsg = e.getMessage();
        } else {
            errorMsg = CodeMsgEnum.LOG_IN_FAIL.getMsg();
        }
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        String responseJson = JackJsonUtil.object2String(ResponseFactory.fail(CodeMsgEnum.LOG_IN_FAIL,errorMsg));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("認證失敗!");
        }
        response.getWriter().write(responseJson);
    }

}

新建登錄認證管理器

實現 AuthenticationProvider ,負責具體的身份認證(一般數據庫認證,在登錄過濾器過濾掉請求后傳入)

@Component
public class UserVerifyAuthenticationProvider implements AuthenticationProvider {

    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserService userService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = (String) authentication.getPrincipal(); // Principal 主體,一般指用戶名
        String passWord = (String) authentication.getCredentials(); //Credentials 網絡憑證,一般指密碼
        //通過賬號去數據庫查詢用戶以及用戶擁有的角色信息
        UserRoleVo userRoleVo = userService.findUserRoleByAccount(userName);
        //數據庫密碼
        String encodedPassword = userRoleVo.getPassWord();
        //credentials憑證即為前端傳入密碼,因為前端一般用Base64加密過所以需要解密。
        String credPassword = new String(Base64Utils.decodeFromString(passWord), StandardCharsets.UTF_8);
        // 驗證密碼:前端明文,數據庫密文
        passwordEncoder = new MD5Util();
        if (!passwordEncoder.matches(credPassword, encodedPassword)) {
            throw new AuthenticationServiceException("賬號或密碼錯誤!");
        }
        //ps:GrantedAuthority對認證主題的應用層面的授權,含當前用戶的權限信息,通常使用角色表示
        List<GrantedAuthority> roles = new LinkedList<>();
        List<Role> roleList = userRoleVo.getRoleList();
        roleList.forEach(role -> {
            SimpleGrantedAuthority roleId = new SimpleGrantedAuthority(role.getRoleId().toString());
            roles.add(roleId);
        });
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, passWord, roles);
        token.setDetails(userRoleVo);//這里可以放用戶的詳細信息
        return token;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return false;
    }
}

新建登錄過濾器

LoginFilter.java繼承UsernamePasswordAuthenticationFilter,負責過濾登錄請求并交由登錄認證管理器進行具體的認證。

public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    private UserVerifyAuthenticationProvider authenticationManager;

    /**
     * @param authenticationManager 認證管理器
     * @param successHandler 認證成功處理類
     * @param failureHandler 認證失敗處理類
     */
    public LoginFilter(UserVerifyAuthenticationProvider authenticationManager,
                       CustomAuthenticationSuccessHandler successHandler,
                       CustomAuthenticationFailureHandler failureHandler) {
        //設置認證管理器(對登錄請求進行認證和授權)
        this.authenticationManager = authenticationManager;
        //設置認證成功后的處理類
        this.setAuthenticationSuccessHandler(successHandler);
        //設置認證失敗后的處理類
        this.setAuthenticationFailureHandler(failureHandler);
        //可以自定義登錄請求的url
        super.setFilterProcessesUrl("/myLogin");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            //轉換請求入參
            UserDTO loginUser = new ObjectMapper().readValue(request.getInputStream(), UserDTO.class);
            //入參傳入認證管理器進行認證
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginUser.getUserName(), loginUser.getPassWord())
            );
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

最后配置到WebSecurityConfig中:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserVerifyAuthenticationProvider authenticationManager;//認證用戶類

    @Autowired
    private CustomAuthenticationSuccessHandler successHandler;//登錄認證成功處理類

    @Autowired
    private CustomAuthenticationFailureHandler failureHandler;//登錄認證失敗處理類

    /**
     * Swagger等靜態資源不進行攔截
     */
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(
                "/*.html",
                "/favicon.ico",
                "/**/*.html",
                "/**/*.css",
                "/**/*.js",
                "/error",
                "/webjars/**",
                "/resources/**",
                "/swagger-ui.html",
                "/swagger-resources/**",
                "/v2/api-docs");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //配置一些不需要登錄就可以訪問的接口
                .antMatchers("/demo/**", "/about/**").permitAll()
                //任何尚未匹配的URL只需要用戶進行身份驗證
                .anyRequest().authenticated()
                .and()
                //配置登錄過濾器
                .addFilter(new LoginFilter(authenticationManager, successHandler, failureHandler))
                .csrf().disable();
    }

}
驗證配置

訪問登錄請求:

圖片

成功進入LoginFilter

圖片圖片

安全頭和登錄返回token

依賴已經引入了,設置session由redis存儲,只需要如下圖配置:
session:
    store-type: redis
    redis:
      namespace: spring:session:admin
    # session 無操作失效時間 30 分鐘
    timeout: 1800

設置token放入返回的header中需要在WebSecurityConfig中加入

/**
 * 配置 HttpSessionIdResolver Bean
 * 登錄之后將會在 Response Header x-auth-token 中 返回當前 sessionToken
 * 將token存儲在前端 每次調用的時候 Request Header x-auth-token 帶上 sessionToken
 */
@Bean
public HttpSessionIdResolver httpSessionIdResolver() {
    return HeaderHttpSessionIdResolver.xAuthToken();
}

關于安全頭信息可以參考:

  • https://docs.spring.io/spring-security/site/docs/5.2.1.BUILD-SNAPSHOT/reference/htmlsingle/#ns-headers

安全請求頭需要設置WebSecurityConfig中加入

protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //配置一些不需要登錄就可以訪問的接口
                .antMatchers("/demo/**", "/about/**").permitAll()
                //任何尚未匹配的URL只需要用戶進行身份驗證
                .anyRequest().authenticated()
                .and()
                //配置登錄過濾器
                .addFilter(new LoginFilter(authenticationManager, successHandler, failureHandler))
                .csrf().disable();
        //配置頭部
        http.headers()
                .contentTypeOptions()
                .and()
                .xssProtection()
                .and()
                //禁用緩存
                .cacheControl()
                .and()
                .httpStrictTransportSecurity()
                .and()
                //禁用頁面鑲嵌frame劫持安全協議  // 防止iframe 造成跨域
                .frameOptions().disable();
    }

進行登錄測試,驗證結果:

圖片圖片

注:響應中有token

查看redis。成功保存進了redis

圖片圖片

接口權限校驗

Spring Security使用FilterSecurityInterceptor過濾器來進行URL權限校驗,實際使用流程大致如下:

正常情況的接口權限判斷:

返回那些可以訪問當前url的角色

1、定義一個MyFilterInvocationSecurityMetadataSource實現FilterInvocationSecurityMetadataSource類,重寫getAttributes方法。

方法的作用是:返回哪些角色可以訪問當前url,這個肯定是從數據庫中獲取。要注意的是對于PathVariable傳參的url,數據庫中存的是這樣的:/getUserByName/{name}。但實際訪問的url中name是具體的值。類似的/user/getUserById 也可以匹配 /user/getUserById?1。

package com.aliyu.security.provider;


import com.aliyu.service.role.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 *@create:
 *@description: 第一步:數據庫查詢所有權限出來:
 * 之所以要所有權限,因為數據庫url和實際請求url并不能直接匹配需要。比方:/user/getUserById 匹配 /user/getUserById?1
 * 第二步:通過httpUrl匹配器找出允許訪問當前請求的角色列表(哪些角色可以訪問此請求)
 */
@Component
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private RoleService roleService;

    /**
     * 返回當前URL允許訪問的角色列表
     * @param object
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //入參轉為HttpServletRequest
        FilterInvocation fi = (FilterInvocation) object;
        HttpServletRequest request = fi.getRequest();
        //從數據庫中查詢系統所有的權限,格式為<"權限url","能訪問url的逗號分隔的roleid">
        List<Map<String, String>> allUrlRoleMap = roleService.getAllUrlRoleMap();
        for (Map<String, String> urlRoleMap : allUrlRoleMap) {
            String url = urlRoleMap.get("url");
            String roles = urlRoleMap.get("roles");
            //new AntPathRequestMatcher創建httpUrl匹配器:里面url匹配規則已經給我們弄好了,
            // 能夠支持校驗PathVariable傳參的url(例如:/getUserByName/{name})
            // 也能支持 /user/getUserById 匹配 /user/getUserById?1
            AntPathRequestMatcher matcher = new AntPathRequestMatcher(url);
            if (matcher.matches(request)){ //當前請求與httpUrl匹配器進行匹配
                return SecurityConfig.createList(roles.split(","));
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}

注:

    1. 方案一是初始化的時候加載所有權限,一次就好了。

    2. 方案二每次請求都會去重新加載系統所有權限,好處就是不用擔心權限修改的問題。(本次實現方案)

    3. 方案三利用Redis緩存

判斷當前用戶是否擁有訪問當前url的角色

定義一個MyAccessDecisionManager:通過實現AccessDecisionManager接口自定義一個決策管理器,判斷是否有訪問權限。上一步MyFilterInvocationSecurityMetadataSource中返回的當前請求可以訪問角色列表會傳到這里的decide方法里面(如果沒有角色的話,不會進入decide方法。

正常情況你訪問的url必然和某個角色關聯,如果沒有關聯就不應該可以訪問)。decide方法傳了當前登錄用戶擁有的角色,通過判斷用戶擁有的角色中是否有一個角色和當前url可以訪問的角色匹配。如果匹配,權限校驗通過。

package com.aliyu.security.provider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

/**
 *@create:
 *@description: 接口權限判斷(根據MyFilterInvocationSecurityMetadataSource獲取到的請求需要的角色
 * 和當前登錄人的角色進行比較)
 */
@Component
public class MyAccessDecisionManager implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        //循環請求需要的角色,只要當前用戶擁有的角色中包含請求需要的角色中的一個,就算通過。
        Iterator<ConfigAttribute> iterator = configAttributes.iterator();
        while(iterator.hasNext()){
            ConfigAttribute configAttribute = iterator.next();
            String needCode = configAttribute.getAttribute();
            //獲取到了登錄用戶的所有角色
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                if (StringUtils.equals(authority.getAuthority(), needCode)) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("當前訪問沒有權限");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
處理匿名用戶訪問無權限資源

1、定義一個CustomAuthenticationEntryPoint實現AuthenticationEntryPoint處理匿名用戶訪問無權限資源(可以理解為未登錄的用戶訪問,確實有些接口是可以不登錄也能訪問的,比較少,我們在WebSecurityConfig已經配置過了。如果多的話,需要另外考慮從數據庫中獲取,并且權限需要加一個標志它為匿名用戶可訪問)。

package com.aliyu.security.handler;

import com.aliyu.common.util.JackJsonUtil;
import com.aliyu.entity.common.vo.ResponseFactory;
import com.aliyu.security.constant.MessageConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import static com.aliyu.entity.common.exception.CodeMsgEnum.MOVED_PERMANENTLY;

/**
 * 未登錄重定向處理器
 * <p>
 * 未登錄狀態下訪問需要登錄的接口
 *
 * @author
 */
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomAuthenticationEntryPoint.class);


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        //原來不需要登錄的接口,現在需要登錄了,所以叫永久移動
        String message = JackJsonUtil.object2String(
                ResponseFactory.fail(MOVED_PERMANENTLY, MessageConstant.NOT_LOGGED_IN)
        );
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("未登錄重定向!");
        }
        response.getWriter().write(message);
    }

}
處理登陸認證過的用戶訪問無權限資源

2、定義一個CustomAccessDeniedHandler 實現AccessDeniedHandler處理登陸認證過的用戶訪問無權限資源。

package com.aliyu.security.handler;

import com.aliyu.common.util.JackJsonUtil;
import com.aliyu.entity.common.exception.CodeMsgEnum;
import com.aliyu.entity.common.vo.ResponseFactory;
import com.aliyu.security.constant.MessageConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;


/**
 * 拒絕訪問處理器(登錄狀態下,訪問沒有權限的方法時會進入此處理器)
 *
 * @author
 */
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomAccessDeniedHandler.class);

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        String message = JackJsonUtil.object2String(
                ResponseFactory.fail(CodeMsgEnum.UNAUTHORIZED, MessageConstant.NO_ACCESS)
        );
        if(LOGGER.isDebugEnabled()){
            LOGGER.debug("沒有權限訪問!");
        }
        response.getWriter().write(message);
    }


}

配置到WebSecurityConfig

package com.aliyu.security.config;

import com.aliyu.filter.LoginFilter;
import com.aliyu.security.handler.*;
import com.aliyu.security.provider.MyAccessDecisionManager;
import com.aliyu.security.provider.MyFilterInvocationSecurityMetadataSource;
import com.aliyu.security.provider.UserVerifyAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.session.web.http.HeaderHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserVerifyAuthenticationProvider authenticationManager;//認證用戶類

    @Autowired
    private CustomAuthenticationSuccessHandler successHandler;//登錄認證成功處理類

    @Autowired
    private CustomAuthenticationFailureHandler failureHandler;//登錄認證失敗處理類

    @Autowired
    private MyFilterInvocationSecurityMetadataSource securityMetadataSource;//返回當前URL允許訪問的角色列表
    @Autowired
    private MyAccessDecisionManager accessDecisionManager;//除登錄登出外所有接口的權限校驗

    /**
     * 密碼加密
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(PasswordEncoder.class)
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置 HttpSessionIdResolver Bean
     * 登錄之后將會在 Response Header x-auth-token 中 返回當前 sessionToken
     * 將token存儲在前端 每次調用的時候 Request Header x-auth-token 帶上 sessionToken
     */
    @Bean
    public HttpSessionIdResolver httpSessionIdResolver() {
        return HeaderHttpSessionIdResolver.xAuthToken();
    }
    /**
     * Swagger等靜態資源不進行攔截
     */
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(
                "/*.html",
                "/favicon.ico",
                "/**/*.html",
                "/**/*.css",
                "/**/*.js",
                "/error",
                "/webjars/**",
                "/resources/**",
                "/swagger-ui.html",
                "/swagger-resources/**",
                "/v2/api-docs");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //配置一些不需要登錄就可以訪問的接口
                .antMatchers("/demo/**", "/about/**").permitAll()
                //任何尚未匹配的URL只需要用戶進行身份驗證
                .anyRequest().authenticated()
                //登錄后的接口權限校驗
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setAccessDecisionManager(accessDecisionManager);
                        object.setSecurityMetadataSource(securityMetadataSource);
                        return object;
                    }
                })
                .and()
                //配置登出處理
                .logout().logoutUrl("/logout")
                .logoutSuccessHandler(new CustomLogoutSuccessHandler())
                .clearAuthentication(true)
                .and()
                //用來解決匿名用戶訪問無權限資源時的異常
                .exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
                //用來解決登陸認證過的用戶訪問無權限資源時的異常
                .accessDeniedHandler(new CustomAccessDeniedHandler())
                .and()
                //配置登錄過濾器
                .addFilter(new LoginFilter(authenticationManager, successHandler, failureHandler))
                .csrf().disable();
        //配置頭部
        http.headers()
                .contentTypeOptions()
                .and()
                .xssProtection()
                .and()
                //禁用緩存
                .cacheControl()
                .and()
                .httpStrictTransportSecurity()
                .and()
                //禁用頁面鑲嵌frame劫持安全協議  // 防止iframe 造成跨域
                .frameOptions().disable();
    }
}

3、其他

特別的,我們認為如果一個接口屬于當前系統,那么它就應該有對應可以訪問的角色。這樣的接口才會被我們限制住。如果一個接口只是在當前系統定義了,而沒有指明它的角色,這樣的接口是不會被我們限制的。

注意點

下面的代碼,本意是想配置一些不需要登錄也可以訪問的接口。

圖片圖片

但是測試的時候發現,任何接口的調用都會進入這里MyFilterInvocationSecurityMetadataSource getAttriButes方法,包括我webSecurityConfig里配置的不需要登錄的url。結果就是不需要登錄的url和沒有配置角色的接口權限一樣待遇,要么都能訪問,要么都不能訪問!!!

圖片

所以如上圖,我在這里配置了不需要登錄的接口(因為不知道如何從webSercurityConfig中獲取,干脆就配置在這里了),去掉了webSercurityConfig中的相應配置。

責任編輯:武曉燕 來源: 一安未來
相關推薦

2018-12-03 12:07:54

南京新動態解決方案

2025-11-18 07:52:13

2011-09-14 10:56:52

服務器虛擬化數據中心

2009-03-12 09:57:24

APC英飛VMware

2017-05-10 14:41:41

存儲

2014-06-09 17:01:06

智能云監控華為

2022-05-03 10:43:43

SpringJava

2009-12-16 13:39:27

Ruby元編程

2022-06-16 10:38:24

URL權限源代碼

2009-04-20 13:47:40

思杰Vmwareesx

2011-06-27 20:48:38

打印機解決方案

2013-01-07 11:05:29

華為解決方案寬帶接入

2021-07-06 13:32:34

零信任網絡安全網絡攻擊

2021-11-10 10:03:18

SpringBootJava代碼

2025-11-07 08:05:18

2024-01-26 08:49:47

ChatGPT搜索方式

2010-04-28 11:48:13

Oracle MySQ

2016-02-29 15:09:54

戴爾云計算

2021-01-12 10:43:22

數字化轉型IT云原生

2025-08-28 01:00:00

點贊
收藏

51CTO技術棧公眾號

无码国产精品96久久久久| 一区二区在线观看免费视频| 精品三级在线| 亚洲激情欧美激情| 欧美高清性xxxxhd| 国产精品久久欧美久久一区| 欧美网站在线| 亚洲人成在线一二| 超碰人人cao| 香蕉视频亚洲一级| 亚洲激情图片小说视频| 日本一区二区不卡高清更新| 国产高清视频免费观看| 视频一区欧美日韩| 欧美激情免费在线| 中文字幕在线观看二区| 日韩美脚连裤袜丝袜在线| 欧美丰满少妇xxxbbb| 男人揉女人奶房视频60分| 成人影欧美片| 久久久久99精品一区| 3d精品h动漫啪啪一区二区| 黄色av网站免费观看| 极品av少妇一区二区| 中文字幕亚洲欧美在线| 在线观看国产网站| 亚洲高清999| 欧美日韩一区二区三区不卡| 国产二区视频在线播放| 欧美极品少妇videossex| 国产精品久久三区| 日韩欧美一区二区三区四区| 少妇高潮久久久| 国产精品一区在线| 成人做爽爽免费视频| 日韩av免费播放| 男人的天堂亚洲| 4p变态网欧美系列| 日韩少妇裸体做爰视频| 欧美精品观看| 欧美人在线视频| 91高清免费看| 亚洲高清资源在线观看| zzjj国产精品一区二区| 欧美自拍偷拍网| 欧美肉体xxxx裸体137大胆| 亚洲精品一区av在线播放| 成人无码www在线看免费| 国产欧美三级电影| 亚洲第一男人av| 亚洲婷婷在线观看| 麻豆成人入口| 精品亚洲va在线va天堂资源站| 欧美性生交xxxxx| 都市激情久久| 日韩精品中文字幕在线观看| 日韩av一二区| 精品国产精品| 日韩在线视频免费观看高清中文| 色偷偷男人天堂| 99久久亚洲精品蜜臀| 久久天天躁狠狠躁夜夜av| 玖玖爱这里只有精品| 欧美三区在线| 欧美激情一级欧美精品| 日韩人妻无码一区二区三区99| 国产日韩专区| 国产精品欧美在线| 国产欧美久久久精品免费| 国产另类ts人妖一区二区| 电影午夜精品一区二区三区| 噜噜噜久久,亚洲精品国产品| 成人av在线一区二区三区| 久久久一本精品99久久精品66| 日韩欧美在线番号| 中文久久乱码一区二区| 一级黄色片播放| 国产精品国精产品一二| 色欧美片视频在线观看 | 污视频网站免费在线观看| 亚洲综合自拍偷拍| 国产主播在线看| 亚瑟国产精品| 亚洲第一中文字幕在线观看| 日韩一区二区a片免费观看| 欧美第十八页| 久久免费高清视频| 中文字幕人妻色偷偷久久| 国产传媒欧美日韩成人| 欧美凹凸一区二区三区视频| 青青青青在线| 精品日本高清在线播放| 日日干夜夜操s8| 成人另类视频| 中文字幕亚洲精品| 影音先锋亚洲天堂| 精品一区二区三区的国产在线播放| 国产精品三区四区| 1024视频在线| 欧美日韩综合视频| 91香蕉视频免费看| 国产一区日韩| 性欧美xxxx视频在线观看| 国产成人精品一区二区色戒| 成人精品一区二区三区四区| 亚洲免费在线精品一区| 麻豆免费在线| 日韩午夜激情免费电影| 日韩一级av毛片| 亚洲人人精品| av一区二区三区四区电影| 韩国中文免费在线视频| 亚洲综合在线观看视频| 天堂视频免费看| 一本久久青青| 午夜精品久久久久久久久久久久| 中文字幕一区二区三区四区免费看| 9i在线看片成人免费| 久久久无码中文字幕久...| 国产精品无码久久久久| 亚洲人成在线观| 女人十八岁毛片| 成人黄色在线看| 国产人妻人伦精品| 57pao成人永久免费| 国产一区二区三区在线观看视频 | 欧美狂野另类xxxxoooo| 一色道久久88加勒比一| 国产精品人人爽人人做我的可爱| av一区二区在线看| 2020国产在线视频| 日韩一区二区电影网| 国产尤物在线播放| 麻豆精品一区二区综合av| 日本不卡久久| 日韩成人亚洲| 国产亚洲a∨片在线观看| 久久99国产综合精品免费| 99久久免费精品高清特色大片| 日韩激情视频一区二区| 亚洲3区在线| 欧美精品videosex极品1| 午夜精品久久久久久久爽 | 中文字幕亚洲欧美日韩在线不卡| 免费黄色片视频| 中文字幕欧美国产| 亚洲一级片免费| 93在线视频精品免费观看| 国产热re99久久6国产精品| 婷婷成人激情| 欧美日韩在线三级| 蜜桃av免费观看| 黑人巨大精品欧美黑白配亚洲| 在线视频亚洲自拍| 国产精品一区二区精品视频观看| 久久精品中文字幕电影| 国产精品无码久久久久成人app| 亚洲视频综合在线| 国产在线a视频| 亚洲黄色影片| 欧美黑人3p| 91九色综合| 久久婷婷国产麻豆91天堂 | 国产亚洲a∨片在线观看| 99re热视频| 日韩美女久久久| 国产日韩视频一区| 久久中文精品| 丰满女人性猛交| 一区二区三区高清在线观看| 欧美一级片在线播放| www视频在线观看免费| 91麻豆精品国产91久久久更新时间| 久久国产精品波多野结衣| 99久久免费视频.com| 天天操,天天操| 欧美日韩三级| 欧美午夜精品久久久久免费视 | 久久av一区二区三区| 亚洲v国产v| 在线播放一区二区精品视频| 欧美一区二区色| 国产秀色在线www免费观看| 欧美精品一区二区久久婷婷| 波多野结衣毛片| 一区二区三区精品在线| 久久精品无码一区| 国产精品66部| 无码日韩人妻精品久久蜜桃| 欧美激情视频一区二区三区在线播放 | 中文字幕一区二区三区不卡| 日本少妇一级片| 视频一区在线播放| 日本男女交配视频| 成人羞羞网站入口| 国产v亚洲v天堂无码| 欧美日韩成人影院| 久久久久国产视频| 欧美性天天影视| 日韩精品在线视频观看| 成人h动漫精品一区二区无码 | 97视频在线播放| 国产日产一区二区| 亚洲人成在线一二| 天天躁日日躁狠狠躁伊人| 欧美日韩国产一二三| 亚洲精品中文字幕乱码三区91| 亚洲精品五月天| 亚洲天堂av中文字幕| 91麻豆国产精品久久| 极品白嫩的小少妇| 激情五月婷婷综合| 亚洲一区二区三区四区五区xx| 日韩视频一区| 97超碰国产精品| 一精品久久久| 正在播放精油久久| 精品国产乱码久久久久久果冻传媒| 国产精品18毛片一区二区| 亚洲人成777| 国产精品亚洲аv天堂网| 天堂在线中文网官网| 久久免费成人精品视频| 亚洲图区一区| 久久成人精品视频| 黄色视屏免费在线观看| 日韩中文字幕免费看| 电影av在线| 亚洲欧美色图片| 精彩国产在线| 亚洲人成在线播放| 黄色在线观看网| 亚洲毛片在线观看| 日本韩国精品一区二区| 亚洲国产欧美一区| 人妻视频一区二区三区| 精品国产乱码91久久久久久网站| 国产高清第一页| 日韩亚洲电影在线| 99热这里是精品| 日韩欧美精品三级| 丁香六月色婷婷| 亚洲成人网av| 视频在线观看你懂的| 亚洲精品视频在线观看视频| 天堂中文在线资源| 日韩久久精品成人| 成人影院免费观看| 中文字幕在线看视频国产欧美| yjizz视频网站在线播放| 伊人伊人伊人久久| 日韩免费啪啪| 免费不卡在线观看av| 国产丝袜视频在线播放| 69影院欧美专区视频| 亚洲精品mv| 国产精品美乳在线观看| 粉嫩一区二区三区在线观看| 91成人免费在线观看| 日韩区欧美区| 精品高清视频| 国产一区二区精品久| 亚洲一区精品视频| 亚洲精品a级片| 黄网站欧美内射| 最新欧美人z0oozo0| 狠狠狠狠狠狠狠| 91免费观看国产| a级在线观看视频| 国产欧美日韩另类一区| 国产精品18在线| 伊人一区二区三区| 分分操这里只有精品| 日韩av有码| 大荫蒂性生交片| 亚洲永久网站| 中文字幕免费高清在线| 国产成人av福利| 中日韩精品一区二区三区| 中文字幕日韩av资源站| 激情综合网五月婷婷| 日本黄色一区二区| 99在线观看免费| 精品偷拍各种wc美女嘘嘘| aaa在线观看| 久久久久久久久亚洲| 欧美成人资源| 99久久99| 国内黄色精品| 日韩精品在线视频免费观看| 丝袜美腿亚洲色图| 国产裸体视频网站| 欧美激情综合五月色丁香 | 国产精品国产三级国产| 精品少妇theporn| 欧美日韩一区二区电影| 婷婷伊人综合中文字幕| 久久精品成人一区二区三区| 韩国成人二区| 91高跟黑色丝袜呻吟在线观看| 五月综合久久| 大地资源网在线观看免费官网| 欧美亚洲专区| 亚洲精品第二页| 中文字幕一区二区三区在线不卡 | 久草一区二区| 中文在线日韩| 成人性生生活性生交12| av亚洲精华国产精华精华| 三上悠亚作品在线观看| 色婷婷香蕉在线一区二区| 丰满少妇一级片| 久久久精品网站| 国产精品久久久久久久久免费高清| 国产在线精品日韩| 黄色在线成人| 超碰在线免费av| 国产精品剧情在线亚洲| 欧美日韩在线视频播放| 亚洲美女激情视频| 欧美a级在线观看| 国产伦精品一区二区三区照片91| 99免费精品| 色一情一区二区| 国产欧美日韩三级| 亚洲图片在线视频| 日韩精品中文字幕在线| ****av在线网毛片| 国产精品国产亚洲精品看不卡15| 亚洲乱码免费伦视频| 欧美日韩中文不卡| 欧美国产欧美亚州国产日韩mv天天看完整| 国产又色又爽又黄的| 日韩av中文字幕在线免费观看| 污视频网站在线免费| 福利视频一区二区三区| 欧美久久影院| 精品人妻二区中文字幕| 亚洲一区二区在线视频| 午夜精品小视频| 久久久爽爽爽美女图片| 99精品国产高清一区二区麻豆| 久久久99精品视频| 国产不卡视频在线播放| 日韩免费一二三区| 亚洲国产成人爱av在线播放| 99在线视频影院| 国产在线资源一区| 乱码第一页成人| 自拍偷拍视频亚洲| 欧美午夜寂寞影院| 黄色小网站在线观看| 91在线色戒在线| 欧美三级视频| 亚洲AV无码国产精品| 91久久精品一区二区三区| 东热在线免费视频| 91久久久久久久久久| 韩国一区二区三区在线观看| 精品无码人妻少妇久久久久久| 精品久久久久久久久久国产| 免费动漫网站在线观看| 国产精品一区二区久久精品| 在线中文字幕第一区| 黑人玩弄人妻一区二区三区| 亚洲h动漫在线| 国产精品一区二区婷婷| 成人天堂噜噜噜| 在线观看一区视频| 亚洲av综合一区二区| 宅男在线国产精品| av福利在线导航| 视频一区二区在线观看| 国产一区二区三区av电影 | 欧美在线一区二区| 国产高清一区二区三区视频| 国产亚洲自拍偷拍| 日一区二区三区| 中文字幕在线有码| 亚洲精品视频中文字幕| 国产精品777777在线播放| 水蜜桃色314在线观看| 中文字幕免费观看一区| www.97av.com| 国产精品69久久| 欧美午夜不卡| 国产精品情侣呻吟对白视频| 精品日韩在线一区| 亚洲a∨精品一区二区三区导航| 男人草女人视频| 国产日韩欧美精品在线| 亚洲精品久久久久avwww潮水| 日韩av123| 国产综合亚洲精品一区二| 国产又黄又粗视频| 亚洲国产成人爱av在线播放| 中文成人在线| 国产精品乱码久久久久| 亚洲成人免费看| 成人黄色网址|