微服务单点登录(springsecurity+jwt+oauth2)

目录

一 设计流程:

1 创建父工程:

1.1添加依赖:

下面为子工程:

1.UI(客户端设计)

2.网关设计(Gatway)

 2.1 创建启动类

 2.2.添加依赖

2.3 添加配置文件:

配件文件的名字为bootstrap.yml

2.4 配置类

3 认证安全模块(auth)

3.1 添加jar包

3.2 创建配置文件配置文件名为bootstrap.yml

3.3 创建启动类

3.4 创建封装类(对用户信息进行封装)

3.5创建配置类(创建JWT令牌配置类,基于这个类实现令牌对象的创建和解析.)

3.6 创建配置类(配置认证管理器(此对象主要负责对客户端输入的用户信息进行认证)

3.7 创建配置类(完成所有配置的组装,在这个配置类中完成认证授权,JWT令牌签发等配置操作)

4.创建资源类(resource)

4.1 导入jar包

4.2创建配置文件

配置文件名字为booystrap.yml

4.3创建启动类

4.4创建配置类(基于过滤器做跨域配置)

4.5创建配置类(资源服务器的配置)

4.6创建配置类(创建JWT令牌配置类,基于这个类实现令牌对象的创建和解析.)

4.7创建业务类(通过此对象实现文件上传服务)


一 设计流程:

 分别设计对应的类,使用聚合模式:

1 创建父工程:

1.1添加依赖:

<properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.3.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR9</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.2.6.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-engine</artifactId>
            </exclusion>
        </exclusions>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>

        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
</dependencies>

下面为子工程:

1.UI(客户端设计)

2.网关设计(Gatway)

 2.1 创建启动类

 2.2.添加依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <!--网关层面的sentinel限流-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
        </dependency>
    </dependencies>


2.3 添加配置文件:

配件文件的名字为bootstrap.yml

server:
  port: 9000
spring:
  application:
    name: sca-resource-gateway
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
      config:
        server-addr: localhost:8848
        file-extension: yml
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
        - id: router01
          uri: lb://sca-resource
          predicates:
            - Path=/sca/resource/upload/**
          filters:
            - StripPrefix=1
        - id: router02
          uri: lb://sca-auth
          predicates:
            #- Path=/auth/login/**  #没要令牌之前
            - Path=/auth/oauth/**   #微服务架构下,需要令牌
          filters:
            - StripPrefix=1
      globalcors: #跨域配置
        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedHeaders: "*"
            allowedMethods: "*"
            allowCredentials: true
    sentinel: #限流设计
      transport:
        dashboard: localhost:8180
      eager: true

2.4 配置类

解决关于跨域问题

package com.jt;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class CorsFilterConfig {
    @Bean
    public CorsWebFilter corsWebFilter(){
        //构建基于url方式的配置
        UrlBasedCorsConfigurationSource source=
                new UrlBasedCorsConfigurationSource();
        //跨域配置
        CorsConfiguration config=new CorsConfiguration();
        //允许所以的跨域ip :port
        config.addAllowedOrigin("*");
        //请求请求头跨域
        config.addAllowedHeader("*");
        //所有的请求方式跨域post/get/..
        config.addAllowedMethod("*");
        //允许携带有效的cookie进行跨域
        config.setAllowCredentials(true);
        source.registerCorsConfiguration("/**",config);
        return new CorsWebFilter(source);
    }
}

2.5创建配置类(自定义限流结果)

package com.jt.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class GatewayConfig {
    public GatewayConfig(){
        //自定义限流结果
        GatewayCallbackManager.setBlockHandler((
                    serverWebExchange, throwable) ->{
                //构建响应数据
                Map<String,Object> map=new HashMap<>();
                map.put("state",429);
                map.put("message","two many request");
                //基于alibaba 的fastjson将对象转换为json
                String jsonStr= JSON.toJSONString(map);//fastjson
                //创建Mono对象,将结果响应到客户端
                return ServerResponse.ok().body(Mono.just(jsonStr),
                        String.class);//String.class表示响应数据类型
            //WebFlux
        });
    }
}
 

3 认证安全模块(auth)

3.1 添加jar包

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    </dependency>
  <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
  </dependency>


</dependencies>

3.2 创建配置文件

配置文件名为bootstrap.yml

server:
  port: 8071
spring:
  application:
    name: sca-auth
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
      config:
        server-addr: localhost:8848


 

3.3 创建启动类

3.4 创建封装类(对用户信息进行封装)对feign接口的调用

package com.jt.auth.service;

import com.jt.auth.feign.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 登录时用户信息的获取和封装会在此对象进行实现,
 * 在页面上点击登录按钮时,会调用这个对象的loadUserByUsername方法,
 * 页面上输入的用户名会传给这个方法的参数
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private RemoteUserService remoteUserService;
    //UserDetails用户封装用户信息(认证和权限信息)
    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        //1.基于用户名查询用户信息(用户名,用户状态,密码,....)
        com.jt.auth.pojo.User user=
                remoteUserService.selectUserByUsername(username);
        //2.查询用户权限信息(后面会访问数据库)
        List<String> permissions=
        remoteUserService.selectUserPermissions(user.getId());
        System.out.println("permissions="+permissions);
       
        List<GrantedAuthority> authorities =
        AuthorityUtils.createAuthorityList(//
                permissions.toArray(new String[]{}));
        //3.对用户信息进行封装
        return new User(username,user.getPassword(),authorities);
    }
}
 

3.5创建配置类(创建JWT令牌配置类,基于这个类实现令牌对象的创建和解析.)

package com.jt.auth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Spring Security是一个主流的Java Web安全框架,它提供了许多现成的安全功能如身份认证、授权和攻击防护。基于Spring Security,我们可以构建出一个安全可靠的Web应用程序。JWT是一种轻量级的身份实体认证方法。在Web应用程序中,用户登录成功之后,服务器会颁发一个JWT令牌给客户端,客户端每次访问时需要携带这个JWT令牌,服务器通过验证JWT令牌的合法性来认证用户身份。OAuth2.0是一个授权框架,它定义了四种角色:资源所有者、客户端、授权服务器和资源服务器。在OAuth2.0框架下,资源服务器只有在通过授权服务器验证后,才会向客户端提供访问资源的权限。 Spring Security提供了对JWTOAuth2.0的支持。通过集成JWTOAuth2.0,我们可以构建出一个更加安全和灵活的Web应用程序。具体地,我们可以使用Spring SecurityJWT机制来实现用户身份认证,并使用OAuth2.0机制来实现对资源的授权。这意味着,我们可以通过Spring Security来管理应用程序中所有的安全相关事务,包括用户的认证和授权。 使用Spring SecurityJWTOAuth2.0,我们可以实现几种不同的认证和授权模式,例如,密码模式、授权码模式和刷新令牌模式等。每种模式都具有自己的使用场景和优缺点。例如,密码模式适用于Web应用程序需要进行用户身份认证的场景,而授权码模式适用于Web应用程序需要访问第三方资源的场景。 综上所述,Spring Security是一个强大的Java Web安全框架,它提供了许多功能,包括身份认证、授权和攻击防护等。使用Spring SecurityJWTOAuth2.0,我们可以实现更加安全和灵活的Web应用程序。通过选择不同的认证和授权模式,我们可以满足不同的使用场景和需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

没伞的孩子努力奔跑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值