Zuul网关 + oauth授权+json web token令牌实现网关中认证与鉴权集成步骤详解. - Go语言中文社区

Zuul网关 + oauth授权+json web token令牌实现网关中认证与鉴权集成步骤详解.


前提: shiro与spring security 都可以实现单体服务器的认证,鉴权.
微服务,分布式项目中解决方案: SSO(单点登录),分布式session.但是权限服务器流量大,还需要考虑存储同步的问题.
Zuul: 网关相当于流量的前门.可以集成zuul+oauth2.0(授权协议)+jwt(json web token)实现代替认证鉴权.原理举例:1.请求微信服务器授权,输入账号密码,确认授权.2.申请微信服务器的令牌.拿到令牌. 3.使用令牌找资源服务器.返回资源.
Jwt的组成: header头部使用jwt的签名算法,Payload载荷:包含自定义或者非自定义的认证信息.Sinature签名:将头部算法与载荷使用点(.)连接,使用头部的签名算法生成签名信息拼接到末尾.
oauth原理:
Zuul网关 + oauth授权+json web token令牌实现网关中认证与鉴权集成步骤详解.

根据分析需要按照该步骤实现开发: 1.eureka-server 2.zuul-server 3.auth-server 4.eureka-client.
1.微服务客户端定义:
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-oauth2</artifactId>
</dependency>
<!-- 引入依赖 : eureka-client. -->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:容器与服务定义:
容器:
@SpringBootApplication
@EnableDiscoveryClient
br/>@EnableResourceServer
@RestController
public class EurekaClient1Application extends ResourceServerConfigurerAdapter {
br/>@Override
public void configure(HttpSecurity http) throws Exception {
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());
}

}br/>服务:
@Controller
public class TestController {

@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网关服务器:
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-oauth2</artifactId>
</dependency>

2.2:bootstrap.yml 认证服务器与路由配置:
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:
oauth2:
client:
access-token-uri: http://localhost:7777/uaa/oauth/token #令牌端点
user-authorization-uri: http://localhost:7777/uaa/oauth/authorize #授权端点
client-id: c-client6-id #OAuth2客户端ID
client-secret: secret #OAuth2客户端密钥
resource:
jwt:
key-value: springcloud123 #使用对称加密方式,默认算法为HS256,如果需要更安全,可使用非对称加密.生成私钥与公钥放这.br/>2.3:容器中的认证规则:
@SpringBootApplication
@EnableZuulProxy
br/>@EnableDiscoveryClient
@EnableOAuth2Sso
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()
            //关闭csrf认证,容易引起***.
            .csrf()
            .disable();
}

}
3.auth-server认证服务器:
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-oauth2</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: truebr/>3.3:认证的实现与token的存储:
@SpringBootApplication
@EnableDiscoveryClient
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();
}

}br/>//------------------------------自定义配置生成token实现存储:
@Configuration
@EnableAuthorizationServer
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.测试:
前提: 启动服务:eureka-server-->zuul-server-->eureka-client-->auth-server.
4.1: 测试访问eureka-client 是否无权直接访问.
4.2:测试访问zuul-server网关:
http://localhost:8090/test/test1?a=10&b=20 : 登录且需要权限.
http://localhost:8090/add?a=10&b=20 : 登录无需权限.

转载于:https://blog.51cto.com/14185725/2370397

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_33969116/article/details/91692576
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-08-27 17:12:05
  • 阅读 ( 2938 )
  • 分类:前端

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢