溫馨提示×

溫馨提示×

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

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

Zuul網(wǎng)關(guān) + oauth授權(quán)+json web token令牌實現(xiàn)網(wǎng)關(guān)中認(rèn)證與鑒權(quán)集成步驟詳解.

發(fā)布時間:2020-07-11 01:00:31 來源:網(wǎng)絡(luò) 閱讀:4604 作者:霸都一匹狼 欄目:編程語言

前提: shiro與spring security 都可以實現(xiàn)單體服務(wù)器的認(rèn)證,鑒權(quán).
微服務(wù),分布式項目中解決方案: SSO(單點登錄),分布式session.但是權(quán)限服務(wù)器流量大,還需要考慮存儲同步的問題.
Zuul: 網(wǎng)關(guān)相當(dāng)于流量的前門.可以集成zuul+oauth3.0(授權(quán)協(xié)議)+jwt(json web token)實現(xiàn)代替認(rèn)證鑒權(quán).原理舉例:1.請求微信服務(wù)器授權(quán),輸入賬號密碼,確認(rèn)授權(quán).2.申請微信服務(wù)器的令牌.拿到令牌. 3.使用令牌找資源服務(wù)器.返回資源.
Jwt的組成: header頭部使用jwt的簽名算法,Payload載荷:包含自定義或者非自定義的認(rèn)證信息.Sinature簽名:將頭部算法與載荷使用點(.)連接,使用頭部的簽名算法生成簽名信息拼接到末尾.
oauth原理:
Zuul網(wǎng)關(guān) + oauth授權(quán)+json web token令牌實現(xiàn)網(wǎng)關(guān)中認(rèn)證與鑒權(quán)集成步驟詳解.

根據(jù)分析需要按照該步驟實現(xiàn)開發(fā): 1.eureka-server 2.zuul-server 3.auth-server 4.eureka-client.
1.微服務(wù)客戶端定義:
1.1:pom.xml:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth3</artifactId>
</dependency>
<!-- 引入依賴 : eureka-client. --><dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
1.2:application.xml:
server.port=8089
spring.application.name=demo-client1
eureka.client.service-url.defaultZone=http://localhost:8080/eureka/
1.3:容器與服務(wù)定義:
容器:
@SpringBootApplication
br/><dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
1.2:application.xml:
server.port=8089
spring.application.name=demo-client1
eureka.client.service-url.defaultZone=http://localhost:8080/eureka/
1.3:容器與服務(wù)定義:
容器:
@SpringBootApplication
br/>@EnableResourceServer
public class EurekaClient1Application extends ResourceServerConfigurerAdapter {@Override
br/>@Override
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/test/test1")
.hasAuthority("WRIGTH_WRITE")
.antMatchers("/**").authenticated();
}

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    resources
            .resourceId("WRIGTH")
            .tokenStore(jwtTokenStore());
}

@Bean
protected JwtAccessTokenConverter jwtTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setSigningKey("springcloud123");
    return converter;
}

@Bean
public TokenStore jwtTokenStore() {
    return new JwtTokenStore(jwtTokenConverter());
}

}服務(wù):
@Controller
br/>服務(wù):
@Controller

@RequestMapping(value = "/test/test1" , method = RequestMethod.GET)
@ResponseBody
public String test1(Integer a , Integer b,HttpServletRequest request){
    System.out.println("----------------header----------------");
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        System.out.println(key + ": " + request.getHeader(key));
    }
    System.out.println("----------------header----------------");
    System.out.println("請求成功...."+a+" ------------- "+ b);
    return "test1..........ok!!!";
}

@GetMapping("/add")
@ResponseBody
public Integer add(Integer a, Integer b){
    return a + b;
}

}

2.zuul-server網(wǎng)關(guān)服務(wù)器:
2.1:pom.xml:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth3</artifactId>
</dependency>

2.2:bootstrap.yml 認(rèn)證服務(wù)器與路由配置:
spring:
application:
name: c-client6
server:
port: 9000
eureka:
client:
serviceUrl:
defaultZone: http://${eureka.host:127.0.0.1}:${eureka.port:8080}/eureka/
instance:
prefer-ip-address: true
zuul:
routes:
demo-client1:
path: /**
serviceId: demo-client1
security:
oauth3:
client:
access-token-uri: http://localhost:7777/uaa/oauth/token #令牌端點
user-authorization-uri: http://localhost:7777/uaa/oauth/authorize #授權(quán)端點
client-id: c-client6-id #OAuth3客戶端ID
client-secret: secret #OAuth3客戶端密鑰
resource:
jwt:
key-value: springcloud123 #使用對稱加密方式,默認(rèn)算法為HS256,如果需要更安全,可使用非對稱加密.生成私鑰與公鑰放這.2.3:容器中的認(rèn)證規(guī)則:
@SpringBootApplication
br/>2.3:容器中的認(rèn)證規(guī)則:
@SpringBootApplication
br/>@EnableDiscoveryClient
public class CClient6Application extends WebSecurityConfigurerAdapter {

public static void main(String[] args) {
    SpringApplication.run(CClient6Application.class, args);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            //這些功能支持免驗證:
            .antMatchers("/login")
            .permitAll()
            //其他任意請求都需要驗證.
            .anyRequest()
            .authenticated()
            .and()
            //關(guān)閉csrf認(rèn)證,容易引起***.
            .csrf()
            .disable();
}

}
3.auth-server認(rèn)證服務(wù)器:
3.1:pom.xml:
<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-oauth3</artifactId>
</dependency>

3.2:bootstrap.yml:
spring:
application:
name: auth-server
server:
port: 7777
servlet:
contextPath: /uaa #web基路徑
eureka:
client:
serviceUrl:
defaultZone: http://${eureka.host:127.0.0.1}:${eureka.port:8080}/eureka/
instance:
prefer-ip-address: true3.3:認(rèn)證的實現(xiàn)與token的存儲:
@SpringBootApplication
br/>3.3:認(rèn)證的實現(xiàn)與token的存儲:
@SpringBootApplication
public class DClient7Application extends WebSecurityConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(DClient7Application.class, args);
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .inMemoryAuthentication()
            .withUser("guest").password("guest").authorities("WRIGTH_READ")
            .and()
            .withUser("admin").password("admin").authorities("WRIGTH_WRITE");
}

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

@Bean
public static NoOpPasswordEncoder passwordEncoder() {
    return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}

}//------------------------------自定義配置生成token實現(xiàn)存儲:
@Configuration
br/>//------------------------------自定義配置生成token實現(xiàn)存儲:
@Configuration
public class OAuthConfiguration extends AuthorizationServerConfigurerAdapter {

@Resource
private AuthenticationManager authenticationManager;

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients
            .inMemory()
            .withClient("c-client6-id")
            .secret("secret")
            .scopes("WRIGTH", "read").autoApprove(true)
            .authorities("WRIGTH_READ", "WRIGTH_WRITE")
            .authorizedGrantTypes("implicit", "refresh_token", "password", "authorization_code");
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints
            .tokenStore(jwtTokenStore())
            .tokenEnhancer(jwtTokenConverter())
            .authenticationManager(authenticationManager);
}

@Bean
public TokenStore jwtTokenStore() {
    return new JwtTokenStore(jwtTokenConverter());
}

@Bean
protected JwtAccessTokenConverter jwtTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setSigningKey("springcloud123");
    return converter;
}

}
4.測試:
前提: 啟動服務(wù):eureka-server-->zuul-server-->eureka-client-->auth-server.
4.1: 測試訪問eureka-client 是否無權(quán)直接訪問.
4.2:測試訪問zuul-server網(wǎng)關(guān):
http://localhost:8090/test/test1?a=10&b=20 : 登錄且需要權(quán)限.
http://localhost:8090/add?a=10&b=20 : 登錄無需權(quán)限.

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI