最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring?Security實現(xiàn)分布式系統(tǒng)授權(quán)方案詳解

 更新時間:2022年02月09日 11:32:16   作者:趙廣陸  
這篇文章主要介紹了Spring?Security實現(xiàn)分布式系統(tǒng)授權(quán),本節(jié)完成注冊中心的搭建,注冊中心采用Eureka,本文通過示例代碼圖文相結(jié)合給大家介紹的非常詳細,需要的朋友可以參考下

1 需求分析

回顧技術(shù)方案如下:

1、UAA認證服務(wù)負責(zé)認證授權(quán)。

2、所有請求經(jīng)過 網(wǎng)關(guān)到達微服務(wù)

3、網(wǎng)關(guān)負責(zé)鑒權(quán)客戶端以及請求轉(zhuǎn)發(fā)

4、網(wǎng)關(guān)將token解析后傳給微服務(wù),微服務(wù)進行授權(quán)。

2 注冊中心

所有微服務(wù)的請求都經(jīng)過網(wǎng)關(guān),網(wǎng)關(guān)從注冊中心讀取微服務(wù)的地址,將請求轉(zhuǎn)發(fā)至微服務(wù)。

本節(jié)完成注冊中心的搭建,注冊中心采用Eureka。

1、創(chuàng)建maven工程

2、pom.xml依賴如下

<?xml version="1.0" encoding="UTF-8"?> 
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-
4.0.0.xsd">
    <parent>
        <artifactId>distributed-security</artifactId>
        <groupId>com.lw.security</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>distributed-security-discovery</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>
</project>

3、配置文件

在resources中配置application.yml

spring: 
    application:
        name: distributed-discovery
server:
    port: 53000 #啟動端口
eureka:
  server:
    enable-self-preservation: false    #關(guān)閉服務(wù)器自我保護,客戶端心跳檢測15分鐘內(nèi)錯誤達到80%服務(wù)會保護,導(dǎo)致別人還認為是好用的服務(wù)
    eviction-interval-timer-in-ms: 10000 #清理間隔(單位毫秒,默認是60*1000)5秒將客戶端剔除的服務(wù)在服務(wù)注冊列表中剔除# 
    shouldUseReadOnlyResponseCache: true #eureka是CAP理論種基于AP策略,為了保證強一致性關(guān)閉此切換CP默認不關(guān)閉 false關(guān)閉
  client: 
    register-with-eureka: false  #false:不作為一個客戶端注冊到注冊中心
    fetch-registry: false      #為true時,可以啟動,但報異常:Cannot execute request on any known server
    instance-info-replication-interval-seconds: 10 
    serviceUrl: 
      defaultZone: http://localhost:${server.port}/eureka/
  instance:
    hostname: ${spring.cloud.client.ip-address}
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${spring.application.instance_id:${server.port}}

啟動類:

@SpringBootApplication
@EnableEurekaServer
public class DiscoveryServer {
   public static void main(String[] args) {
      SpringApplication.run(DiscoveryServer.class, args);
  }
}

3 網(wǎng)關(guān)

網(wǎng)關(guān)整合 OAuth2.0 有兩種思路,一種是認證服務(wù)器生成jwt令牌, 所有請求統(tǒng)一在網(wǎng)關(guān)層驗證,判斷權(quán)限等操作;另一種是由各資源服務(wù)處理,網(wǎng)關(guān)只做請求轉(zhuǎn)發(fā)。

我們選用第一種。我們把API網(wǎng)關(guān)作為OAuth2.0的資源服務(wù)器角色,實現(xiàn)接入客戶端權(quán)限攔截、令牌解析并轉(zhuǎn)發(fā)當前登錄用戶信息(jsonToken)給微服務(wù),這樣下游微服務(wù)就不需要關(guān)心令牌格式解析以及OAuth2.0相關(guān)機制了。

API網(wǎng)關(guān)在認證授權(quán)體系里主要負責(zé)兩件事:

(1)作為OAuth2.0的資源服務(wù)器角色,實現(xiàn)接入方權(quán)限攔截。

(2)令牌解析并轉(zhuǎn)發(fā)當前登錄用戶信息(明文token)給微服務(wù)

微服務(wù)拿到明文token(明文token中包含登錄用戶的身份和權(quán)限信息)后也需要做兩件事:

(1)用戶授權(quán)攔截(看當前用戶是否有權(quán)訪問該資源)

(2)將用戶信息存儲進當前線程上下文(有利于后續(xù)業(yè)務(wù)邏輯隨時獲取當前用戶信息)

3.1 創(chuàng)建工程

1、pom.xml

<?xml version="1.0" encoding="UTF-8"?> 
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-
4.0.0.xsd">
    <parent>
        <artifactId>distributed-security</artifactId>
        <groupId>com.lw.security</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>distributed-security-gateway</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId> 
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>com.netflix.hystrix</groupId>
            <artifactId>hystrix-javanica</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-jwt</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.interceptor</groupId>
            <artifactId>javax.interceptor-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

2、配置文件

配置application.properties

spring.application.name=gateway-server
server.port=53010
spring.main.allow-bean-definition-overriding = true
logging.level.root = info
logging.level.org.springframework = info
zuul.retryable = true
zuul.ignoredServices = *
zuul.add-host-header = true
zuul.sensitiveHeaders = *
zuul.routes.uaa-service.stripPrefix = false
zuul.routes.uaa-service.path = /uaa/**
zuul.routes.order-service.stripPrefix = false
zuul.routes.order-service.path = /order/**
eureka.client.serviceUrl.defaultZone = http://localhost:53000/eureka/
eureka.instance.preferIpAddress = true
eureka.instance.instance-id = ${spring.application.name}:${spring.cloud.client.ip-address}:${spring.application.instance_id:${server.port}}
management.endpoints.web.exposure.include = refresh,health,info,env
feign.hystrix.enabled = true
feign.compression.request.enabled = true
feign.compression.request.mime-types[0] = text/xml
feign.compression.request.mime-types[1] = application/xml
feign.compression.request.mime-types[2] = application/json
feign.compression.request.min-request-size = 2048
feign.compression.response.enabled = true

統(tǒng)一認證服務(wù)(UAA)與統(tǒng)一用戶服務(wù)都是網(wǎng)關(guān)下微服務(wù),需要在網(wǎng)關(guān)上新增路由配置:

zuul.routes.uaa-service.stripPrefix = false
zuul.routes.uaa-service.path = /uaa/**

zuul.routes.user-service.stripPrefix = false
zuul.routes.user-service.path = /order/**

上面配置了網(wǎng)關(guān)接收的請求url若符合/order/**表達式,將被被轉(zhuǎn)發(fā)至order-service(統(tǒng)一用戶服務(wù))。

啟動類:

@SpringBootApplication 
@EnableZuulProxy
@EnableDiscoveryClient
public class GatewayServer {
    public static void main(String[] args) {
        SpringApplication.run(GatewayServer.class, args);
    }
}

3.2 token配置

前面也介紹了,資源服務(wù)器由于需要驗證并解析令牌,往往可以通過在授權(quán)服務(wù)器暴露check_token的Endpoint來完成,而我們在授權(quán)服務(wù)器使用的是對稱加密的jwt,因此知道密鑰即可,資源服務(wù)與授權(quán)服務(wù)本就是對稱設(shè)計,那我們把授權(quán)服務(wù)的TokenConfig兩個類拷貝過來就行 。

@Configuration
public class TokenConfig {
  private String SIGNING_KEY = "uaa123";
    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter()); 
    }
   @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(SIGNING_KEY); //對稱秘鑰,資源服務(wù)器使用該秘鑰來解密
        return converter;
    }
}

3.3 配置資源服務(wù)

在ResouceServerConfig中定義資源服務(wù)配置,主要配置的內(nèi)容就是定義一些匹配規(guī)則,描述某個接入客戶端需要什么樣的權(quán)限才能訪問某個微服務(wù),如:

@Configuration
public class ResouceServerConfig {
    public static final String RESOURCE_ID = "res1";
    /**
     * 統(tǒng)一認證服務(wù)(UAA) 資源攔截
     */
    @Configuration
    @EnableResourceServer
    public class UAAServerConfig extends
            ResourceServerConfigurerAdapter {
        @Autowired
        private TokenStore tokenStore;
        @Override
        public void configure(ResourceServerSecurityConfigurer resources){
            resources.tokenStore(tokenStore).resourceId(RESOURCE_ID)
                    .stateless(true);
        }
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/uaa/**").permitAll();
        }
    }
    /**
     *  訂單服務(wù)
     */

@Configuration
    @EnableResourceServer
    public class OrderServerConfig extends
        ResourceServerConfigurerAdapter {
            @Autowired
            private TokenStore tokenStore;
        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources.tokenStore(tokenStore).resourceId(RESOURCE_ID)
                    .stateless(true);
        }
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    .antMatchers("/order/**").access("#oauth2.hasScope('ROLE_API')");
        }
    }
}

上面定義了兩個微服務(wù)的資源,其中:

UAAServerConfig指定了若請求匹配/uaa/**網(wǎng)關(guān)不進行攔截。

OrderServerConfig指定了若請求匹配/order/**,也就是訪問統(tǒng)一用戶服務(wù),接入客戶端需要有scope中包含read,并且authorities(權(quán)限)中需要包含ROLE_USER。

由于res1這個接入客戶端,read包括ROLE_ADMIN,ROLE_USER,ROLE_API三個權(quán)限。

3.4 安全配置

@Configuration 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/**").permitAll()
                .and().csrf().disable();
    }
}

4 轉(zhuǎn)發(fā)明文token給微服務(wù)

通過Zuul過濾器的方式實現(xiàn),目的是讓下游微服務(wù)能夠很方便的獲取到當前的登錄用戶信息(明文token)

( 1)實現(xiàn)Zuul前置過濾器,完成當前登錄用戶信息提取,并放入轉(zhuǎn)發(fā)微服務(wù)的request中

/**
 * token傳遞攔截
 */
public class AuthFilter extends ZuulFilter {
    @Override
    public boolean shouldFilter() {
        return true;
    }
    @Override
    public String filterType() {
        return "pre";
    }
    @Override
    public int filterOrder() {
        return 0;
    }
    @Override
    public Object run() {
        /**
         * 1.獲取令牌內(nèi)容
         */
        RequestContext ctx = RequestContext.getCurrentContext();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(!(authentication instanceof OAuth2Authentication)){ // 無token訪問網(wǎng)關(guān)內(nèi)資源的情況,目前僅有uua服務(wù)直接暴露
            return null;
        }
        OAuth2Authentication oauth2Authentication  = (OAuth2Authentication)authentication;
        Authentication userAuthentication = oauth2Authentication.getUserAuthentication();
        Object principal = userAuthentication.getPrincipal();
        /**
         * 2.組裝明文token,轉(zhuǎn)發(fā)給微服務(wù),放入header,名稱為json-token
         */
        List<String> authorities = new ArrayList();
        userAuthentication.getAuthorities().stream().forEach(s ->authorities.add(((GrantedAuthority) s).getAuthority()));
        OAuth2Request oAuth2Request = oauth2Authentication.getOAuth2Request();
        Map<String, String> requestParameters = oAuth2Request.getRequestParameters();
        Map<String,Object> jsonToken = new HashMap<>(requestParameters);
        if(userAuthentication != null){
            jsonToken.put("principal",userAuthentication.getName());
            jsonToken.put("authorities",authorities);
        }
        ctx.addZuulRequestHeader("json-token", EncryptUtil.encodeUTF8StringBase64(JSON.toJSONString(jsonToken)));
        return null;
   }
}

common包下建EncryptUtil類 UTF8互轉(zhuǎn)Base64

public class EncryptUtil {
    private static final Logger logger = LoggerFactory.getLogger(EncryptUtil.class);

    public static String encodeBase64(byte[] bytes){
        String encoded = Base64.getEncoder().encodeToString(bytes);
        return encoded;
    }
    public static byte[]  decodeBase64(String str){
        byte[] bytes = null;
        bytes = Base64.getDecoder().decode(str);
        return bytes;
    public static String encodeUTF8StringBase64(String str){
        String encoded = null;
        try {
            encoded = Base64.getEncoder().encodeToString(str.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            logger.warn("不支持的編碼格式",e);
        }
    public static String  decodeUTF8StringBase64(String str){
        String decoded = null;
        byte[] bytes = Base64.getDecoder().decode(str);
            decoded = new String(bytes,"utf-8");
        }catch(UnsupportedEncodingException e){
        return decoded;
    public static String encodeURL(String url) {
    	String encoded = null;
		try {
			encoded =  URLEncoder.encode(url, "utf-8");
		} catch (UnsupportedEncodingException e) {
			logger.warn("URLEncode失敗", e);
		}
		return encoded;
	}
	public static String decodeURL(String url) {
    	String decoded = null;
			decoded = URLDecoder.decode(url, "utf-8");
			logger.warn("URLDecode失敗", e);
		return decoded;
    public static void main(String [] args){
        String str = "abcd{'a':'b'}";
        String encoded = EncryptUtil.encodeUTF8StringBase64(str);
        String decoded = EncryptUtil.decodeUTF8StringBase64(encoded);
        System.out.println(str);
        System.out.println(encoded);
        System.out.println(decoded);
        String url = "== wo";
        String urlEncoded = EncryptUtil.encodeURL(url);
        String urlDecoded = EncryptUtil.decodeURL(urlEncoded);
        
        System.out.println(url);
        System.out.println(urlEncoded);
        System.out.println(urlDecoded);
}

( 2)將filter納入spring 容器:

配置AuthFilter

@Configuration
public class ZuulConfig {
    @Bean
    public AuthFilter preFileter() {
        return new AuthFilter();
    }
    @Bean
    public FilterRegistrationBean corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setMaxAge(18000L);
        source.registerCorsConfiguration("/**", config);
        CorsFilter corsFilter = new CorsFilter(source);
        FilterRegistrationBean bean = new FilterRegistrationBean(corsFilter);
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }
}

5 微服務(wù)用戶鑒權(quán)攔截

當微服務(wù)收到明文token時,應(yīng)該怎么鑒權(quán)攔截呢?自己實現(xiàn)一個filter?自己解析明文token,自己定義一套資源訪問策略?能不能適配Spring Security呢,是不是突然想起了前面我們實現(xiàn)的Spring Security基于token認證例子。咱們還拿統(tǒng)一用戶服務(wù)作為網(wǎng)關(guān)下游微服務(wù),對它進行改造,增加微服務(wù)用戶鑒權(quán)攔截功能。

(1)增加測試資源

OrderController增加以下endpoint

@PreAuthorize("hasAuthority('p1')")
    @GetMapping(value = "/r1")
    public String r1(){
        UserDTO user = (UserDTO)
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
         return user.getUsername() + "訪問資源1";
    }
    @PreAuthorize("hasAuthority('p2')")
    @GetMapping(value = "/r2")
    public String r2(){//通過Spring Security API獲取當前登錄用戶
        UserDTO user =
(UserDTO)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return user.getUsername() + "訪問資源2";
    }

model包下加實體類UserDto

@Data
public class UserDTO {
    private String id;
    private String username;
    private String mobile;
    private String fullname;
}

(2)Spring Security配置

開啟方法保護,并增加Spring配置策略,除了/login方法不受保護(統(tǒng)一認證要調(diào)用),其他資源全部需要認證才能訪問。

@Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/**").access("#oauth2.hasScope('ROLE_ADMIN')")
                .and().csrf().disable()
                 .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

綜合上面的配置,咱們共定義了三個資源了,擁有p1權(quán)限可以訪問r1資源,擁有p2權(quán)限可以訪問r2資源,只要認證通過就能訪問r3資源。

(3)定義filter攔截token,并形成Spring Security的Authentication對象

@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse
httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
               String token = httpServletRequest.getHeader("json-token");
        if (token != null){
            //1.解析token
            String json = EncryptUtil.decodeUTF8StringBase64(token);
            JSONObject userJson = JSON.parseObject(json);
            UserDTO user = new UserDTO();
            user.setUsername(userJson.getString("principal"));
            JSONArray authoritiesArray = userJson.getJSONArray("authorities");
            String  [] authorities = authoritiesArray.toArray( new
String[authoritiesArray.size()]);
            //2.新建并填充authentication
            UsernamePasswordAuthenticationToken authentication = new
UsernamePasswordAuthenticationToken(
                    user, null, AuthorityUtils.createAuthorityList(authorities));
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                    httpServletRequest));
            //3.將authentication保存進安全上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}

經(jīng)過上邊的過慮 器,資源 服務(wù)中就可以方便到的獲取用戶的身份信息:

UserDTO user = (UserDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

還是三個步驟:

1.解析token

2.新建并填充authentication

3.將authentication保存進安全上下文

剩下的事兒就交給Spring Security好了。

6 集成測試

注意:記得uaa跟order的pom導(dǎo)入eurika坐標,以及application.properties配置eurika

本案例測試過程描述:

1、采用OAuth2.0的密碼模式從UAA獲取token

2、使用該token通過網(wǎng)關(guān)訪問訂單服務(wù)的測試資源

(1)過網(wǎng)關(guān)訪問uaa的授權(quán)及獲取令牌,獲取token。注意端口是53010,網(wǎng)關(guān)的端口。

如授權(quán) endpoint:

http://localhost:53010/uaa/oauth/authorize?response_type=code&client_id=c1 

令牌endpoint

http://localhost:53010/uaa/oauth/token

(2)使用Token過網(wǎng)關(guān)訪問訂單服務(wù)中的r1-r2測試資源進行測試。

結(jié)果:

使用張三token訪問p1,訪問成功

使用張三token訪問p2,訪問失敗

使用李四token訪問p1,訪問失敗

使用李四token訪問p2,訪問成功

符合預(yù)期結(jié)果。

(3)破壞token測試

無token測試返回內(nèi)容:

{ 
    "error": "unauthorized",
    "error_description": "Full authentication is required to access this resource"
}

破壞token測試返回內(nèi)容:

{ 
    "error": "invalid_token",
    "error_description": "Cannot convert access token to JSON"
}

7 擴展用戶信息

7.1 需求分析

目前jwt令牌存儲了用戶的身份信息、權(quán)限信息,網(wǎng)關(guān)將token明文化轉(zhuǎn)發(fā)給微服務(wù)使用,目前用戶身份信息僅包括了用戶的賬號,微服務(wù)還需要用戶的ID、手機號等重要信息。

所以,本案例將提供擴展用戶信息的思路和方法,滿足微服務(wù)使用用戶信息的需求。

下邊分析JWT令牌中擴展用戶信息的方案:

在認證階段DaoAuthenticationProvider會調(diào)用UserDetailService查詢用戶的信息,這里是可以獲取到齊全的用戶信息的。由于JWT令牌中用戶身份信息來源于UserDetails,UserDetails中僅定義了username為用戶的身份信息,這里有兩個思路:第一是可以擴展UserDetails,使之包括更多的自定義屬性,第二也可以擴展username的內(nèi)容,比如存入json數(shù)據(jù)內(nèi)容作為username的內(nèi)容。相比較而言,方案二比較簡單還不用破壞UserDetails的結(jié)構(gòu),我們采用方案二。

7.2 修改UserDetailService

從數(shù)據(jù)庫查詢到user,將整體user轉(zhuǎn)成json存入userDetails對象。

@Override 
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    //登錄賬號
    System.out.println("username="+username);
    //根據(jù)賬號去數(shù)據(jù)庫查詢...
    UserDto user = userDao.getUserByUsername(username);
    if(user == null){
        return null;
    }
    //查詢用戶權(quán)限
    List<String> permissions = userDao.findPermissionsByUserId(user.getId());
    String[] perarray = new String[permissions.size()];
    permissions.toArray(perarray);
    //創(chuàng)建userDetails
    //這里將user轉(zhuǎn)為json,將整體user存入userDetails
    String principal = JSON.toJSONString(user);
    UserDetails userDetails =
User.withUsername(principal).password(user.getPassword()).authorities(perarray).build();
    return userDetails;
}

7.3 修改資源服務(wù)過慮器

資源服務(wù)中的過慮 器負責(zé) 從header中解析json-token,從中即可拿網(wǎng)關(guān)放入的用戶身份信息,部分關(guān)鍵代碼如下:

... 
if (token != null){
    //1.解析token
    String json = EncryptUtil.decodeUTF8StringBase64(token);
    JSONObject userJson = JSON.parseObject(json);
    //取出用戶身份信息
    String principal = userJson.getString("principal");
    //將json轉(zhuǎn)成對象
    UserDTO userDTO = JSON.parseObject(principal, UserDTO.class);
    JSONArray authoritiesArray = userJson.getJSONArray("authorities");
    ...

以上過程就完成自定義用戶身份信息的方案。

到此這篇關(guān)于Spring Security實現(xiàn)分布式系統(tǒng)授權(quán)的文章就介紹到這了,更多相關(guān)Spring Security分布式授權(quán)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot整合MyBatis-Plus的示例代碼

    SpringBoot整合MyBatis-Plus的示例代碼

    這篇文章主要介紹了SpringBoot整合MyBatis-Plus的示例代碼,使用?MyBatis-Plus 可以減少大量的開發(fā)時間,單表的增刪改查可以不用寫 sql 語句,本文主要介紹整合需要主要事項,需要的朋友可以參考下
    2022-03-03
  • spring boot自定義配置時在yml文件輸入有提示問題及解決方案

    spring boot自定義配置時在yml文件輸入有提示問題及解決方案

    自定義一個配置類,然后在yml文件具體配置值時,一般不會有提示,今天小編給大家分享spring boot自定義配置時在yml文件輸入有提示問題,感興趣的朋友一起看看吧
    2023-10-10
  • MyBatis延遲加載與立即加載案例教程

    MyBatis延遲加載與立即加載案例教程

    這篇文章主要介紹了MyBatis延遲加載與立即加載案例教程,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下
    2021-07-07
  • 如何在springboot中配置和使用mybatis-plus

    如何在springboot中配置和使用mybatis-plus

    這篇文章主要給大家介紹了關(guān)于如何在springboot中配置和使用mybatis-plus的相關(guān)資料,MyBatis?Plus是MyBatis的增強版,旨在提供更多便捷的特性,減少開發(fā)工作,同時保留了MyBatis的靈活性和強大性能,需要的朋友可以參考下
    2023-11-11
  • Java關(guān)鍵字this使用方法詳細講解(通俗易懂)

    Java關(guān)鍵字this使用方法詳細講解(通俗易懂)

    這篇文章主要介紹了Java關(guān)鍵字this使用方法的相關(guān)資料,Java關(guān)鍵字this主要用于在方法體內(nèi)引用當前對象,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2025-01-01
  • 詳解Java ES多節(jié)點任務(wù)的高效分發(fā)與收集實現(xiàn)

    詳解Java ES多節(jié)點任務(wù)的高效分發(fā)與收集實現(xiàn)

    ElasticSearch 是一個高可用開源全文檢索和分析組件。提供存儲服務(wù),搜索服務(wù),大數(shù)據(jù)準實時分析等。一般用于提供一些提供復(fù)雜搜索的應(yīng)用
    2021-06-06
  • 通過Java?Reflection實現(xiàn)編譯時注解正確處理方法

    通過Java?Reflection實現(xiàn)編譯時注解正確處理方法

    Java注解是一種標記在JDK5及以后的版本中引入,用于Java語言中向程序添加元數(shù)據(jù)的方法,這篇文章主要介紹了通過Java?Reflection實現(xiàn)編譯時注解處理方法,需要的朋友可以參考下
    2023-06-06
  • SpringBoot+vue+Axios實現(xiàn)Token令牌的詳細過程

    SpringBoot+vue+Axios實現(xiàn)Token令牌的詳細過程

    Token是在服務(wù)端產(chǎn)生的,前端可以使用用戶名/密碼向服務(wù)端請求認證(登錄),服務(wù)端認證成功,服務(wù)端會返回?Token?給前端,Token可以使用自己的算法自定義,本文給大家介紹SpringBoot+vue+Axios實現(xiàn)Token令牌,感興趣的朋友一起看看吧
    2023-10-10
  • Java 8中Stream API的這些奇技淫巧!你Get了嗎?

    Java 8中Stream API的這些奇技淫巧!你Get了嗎?

    這篇文章主要介紹了Java 8中Stream API的這些奇技淫巧!你Get了嗎?文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • 解析Java按值傳遞還是按引用傳遞

    解析Java按值傳遞還是按引用傳遞

    這篇文章主要介紹了解析Java按值傳遞還是按引用傳遞,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01

最新評論

桓仁| 军事| 临澧县| 迁安市| 什邡市| 博罗县| 法库县| 高安市| 万州区| 五河县| 赞皇县| 金昌市| 绥中县| 汉阴县| 凤庆县| 兖州市| 鲁山县| 敦化市| 南召县| 扶风县| 东城区| 武城县| 桂林市| 宜春市| 长泰县| 新巴尔虎右旗| 舞钢市| 临清市| 长寿区| 罗江县| 苍梧县| 龙州县| 株洲市| 迁西县| 龙陵县| 当雄县| 临海市| 吉木萨尔县| 柳江县| 保定市| 黑山县|