springsecurity oauth2的单点登录

springsecurity oauth2的单点登录

  1. 写一个授权服务器
    建一个sso的项目

pom.xml

 <dependencies>
        <!-- /spring-security-oauth2-autoconfigure -->
        <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</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-oauth2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

WebSecurityConfigurerAdapter

@Configuration
@Order(1) //这个要先装配到 容器, 顺序要在前面, 千万不能少
//@EnableWebSecurity
public class CztSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
        auth.userDetailsService(userDetailsService());
    }


    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
//        return super.userDetailsService();

        InMemoryUserDetailsManager userDetailsManager=new InMemoryUserDetailsManager();
        userDetailsManager.createUser(User.withUsername("czt")
        .password(passwordEncoder().encode("123456"))
                .authorities("ROLE_P").build()
        );
        userDetailsManager.createUser(User.withUsername("tom")
                .password(passwordEncoder().encode("123456"))
                .authorities("ROLE_G").build()
        );
        return userDetailsManager;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.csrf().disable();
        http.requestMatchers()
                .antMatchers("/login","/oauth/authorize") //注意: 放行
                .and()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll();

    }
}

AuthorizationServerConfigurerAdapter


@Configuration
@EnableAuthorizationServer //开启授权服务器
public class Oauth2serverConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
   private BCryptPasswordEncoder passwordEncoder;
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
//        super.configure(security);
        security
                .tokenKeyAccess("permitAll()") //获取token放行
                .checkTokenAccess("isAuthenticated()") //
                .allowFormAuthenticationForClients();

    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//        super.configure(clients);
        clients
                .inMemory()
                .withClient("c1")//可以申请token的人
                .secret(passwordEncoder.encode("8888"))
                .authorizedGrantTypes("password", "authorization_code", "client_credentials", "implicit", "refresh_token")
                .scopes("all","header")
                .autoApprove(true)
                .redirectUris("http://127.0.0.1:9001/app1/login","http://127.0.0.1:9002/app2/login")
                .and()
                .withClient("czt")//可以申请token的人
                .secret(passwordEncoder.encode("9999"))
                .authorizedGrantTypes("password","authorization_code","client_credentials", "implicit", "refresh_token")
                .scopes("all","header")
                .autoApprove(true)
                .redirectUris("http://127.0.0.1:9001/app1/login","http://127.0.0.1:9002/app2/login");

//        http://localhost:8080/oauth/authorize?client_id=czt&response_type=code&redirect=http://www.baidu.com
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        super.configure(endpoints);
    }
}

主函数

@SpringBootApplication
@EnableResourceServer//打开资源服务器
public class DemoSsoApplication {

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

}

2. 写两个资源服务器

建一个 app1和app2项目
内容雷同

pom文件

<dependencies>
        <!-- /spring-security-oauth2-autoconfigure -->
        <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

config 所要继承的父类 WebSecurityConfigurerAdapter

@Override
    public void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**")
                .authorizeRequests()
                .antMatchers("/login**") //注意: 放行
                .permitAll()
                .anyRequest()
                .authenticated();
    }

HelloController

@Controller
public class HelloController {


    @ResponseBody
    @GetMapping("/info")
    public Authentication authentication(Authentication authentication) {
        System.out.println(authentication);
        return authentication;
    }
    @ResponseBody
    @GetMapping("/hello")
    public String hello(String name) {
        return "登录的用户名:" + name;
    }
    @RequestMapping({"/index", "/"})
    public String indexPage() {
        return "index";

    }
}

最主要就是这个application.properties

server.port=9001
server.servlet.context-path=/app1

server.servlet.session.cookie.name=czt

security.oauth2.client.client-id=czt
security.oauth2.client.client-secret=9999

#授权码去授权服务器哪里获取 token
security.oauth2.client.access-token-uri=http://127.0.0.1:8080/oauth/token

security.oauth2.client.user-authorization-uri=http://127.0.0.1:8080/oauth/authorize
#以后每次到授权服务器检查
security.oauth2.resource.token-info-uri=http://127.0.0.1:8080/oauth/check_token
#从授权服务器获取 UserDetails
# 在授权服务器中要有一个controller /user里面返回了Principal对象
#Principal 对象为当前登录的对象
security.oauth2.resource.user-info-uri=http://127.0.0.1:8080/user

如果再写一个app2,就把端口号改一下,

server.port=9002
server.servlet.context-path=/app2

server.servlet.session.cookie.name=czt

security.oauth2.client.client-id=czt
security.oauth2.client.client-secret=9999

#授权码去授权服务器哪里获取 token
security.oauth2.client.access-token-uri=http://127.0.0.1:8080/oauth/token

security.oauth2.client.user-authorization-uri=http://127.0.0.1:8080/oauth/authorize
#以后每次到授权服务器检查
security.oauth2.resource.token-info-uri=http://127.0.0.1:8080/oauth/check_token
#从授权服务器获取 UserDetails
# 在授权服务器中要有一个controller /user里面返回了Principal对象
#Principal 对象为当前登录的对象
security.oauth2.resource.user-info-uri=http://127.0.0.1:8080/user
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值