SpringCloud OAuth2认证服务搭建

一、SpringCloud OAuth2认证服务搭建
二、SpringCloud OAuth2资源服务搭建
三、SpringCloud OAuth2模拟第三方服务

一. 创建MAVEN项目完成认证服务配置

1.pom中依赖如下:
<?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>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud-auth-server</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <!--排除tomcat依赖-->
                <exclusion>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                    <groupId>org.springframework.boot</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--undertow容器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>
        <!--spring security 、oauth、jwt依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
            <version>2.1.2.RELEASE</version>
        </dependency>
    </dependencies>

</project>
2.创建项目入口类:
package cn.itxsl;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @program: example
 * @description: 认证中心
 * @author: itxsl
 * @create: 2019-04-25 12:26
 **/
@SpringBootApplication
public class AuthApplication {

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

}

3.创建认证服务器配置中心:
package cn.itxsl.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.*;

/**
 * @program: itxsl-cloud
 * @description: 认证服务配置
 * @author: itxsl
 * @create: 2019-04-23 15:45
 **/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfigure extends AuthorizationServerConfigurerAdapter {

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //默认是不支持表单提交,这里修改提交权限
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
        super.configure(security);
    }




    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService());
        super.configure(clients);
    }

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.setClientDetailsService(clientDetailsService());
        endpoints.authenticationManager(authenticationManager)
                .accessTokenConverter(jwtAccessTokenConverter());//这里配置JWT加密,如果不想要JWT,将此行及jwtAccessTokenConverter()方法删除即可
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        KeyPair keyPair = new KeyStoreKeyFactory(
                new ClassPathResource("keystore.jks"), "foobar".toCharArray())//jks可用jdk 工具生成
                .getKeyPair("test");
        converter.setKeyPair(keyPair);
        return converter;
    }

    //正常情况,这个ClientDetailsService是在业务层,继承ClientDetailsService接口,并实现loadClientByClientId(String s)方法
    public  ClientDetailsService clientDetailsService(){
        return new ClientDetailsService() {
            @Override
            public ClientDetails loadClientByClientId(String s) throws ClientRegistrationException {
                return new ClientDetails() {
                    @Override
                    public String getClientId() {
                        return "itxsl";
                    }

                    @Override
                    public Set<String> getResourceIds() {
                        return null;
                    }

                    @Override
                    public boolean isSecretRequired() {
                        return true;
                    }

                    @Override
                    public String getClientSecret() {
                        return "itxsl";
                    }

                    @Override
                    public boolean isScoped() {
                        return true;
                    }

                    @Override
                    public Set<String> getScope() {
                        HashSet<String> strings = new HashSet<>();
                        strings.add("all");
                        return strings;
                    }

                    @Override//这里配置支持哪几种授权模式
                    public Set<String> getAuthorizedGrantTypes() {
                        Set<String> strings = new HashSet<>();
                        strings.add("code");
                        strings.add("authorization_code");
                        strings.add("refresh_token");
                        strings.add("password");
                        return strings;
                    }

                    @Override
                    public Set<String> getRegisteredRedirectUri() {
                        Set<String> strings = new HashSet<>();
                        strings.add("http://localhost:7003/auth/account");//这里是重定向地址及最后code授权码返回地址
                        return strings;
                    }

                    @Override
                    public Collection<GrantedAuthority> getAuthorities() {
                        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
                        grantedAuthorityList.add(new GrantedAuthority() {
                            @Override
                            public String getAuthority() {
                                return "itxsl";
                            }
                        });
                        return grantedAuthorityList;
                    }

                    @Override
                    public Integer getAccessTokenValiditySeconds() {
                        return 3600;
                    }

                    @Override
                    public Integer getRefreshTokenValiditySeconds() {
                        return 3600;
                    }

                    @Override
                    public boolean isAutoApprove(String s) {
                        return true;
                    }

                    @Override
                    public Map<String, Object> getAdditionalInformation() {
                        return null;
                    }
                };
            }
        };
    }
}

4.创建认证服务器用户安全配置中心:
package cn.itxsl.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
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.security.crypto.password.PasswordEncoder;

import java.util.Collection;

/**
 * @program: itxsl-cloud
 * @description: 账号认证中心
 * @author: itxsl
 * @create: 2019-04-23 15:53
 **/
@EnableWebSecurity
public class WebSecurityConfigure  extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService(){
        return  new UserDetailsService() {//这里一般都是在业务层,实现UserDetailsService中loadUserByUsername(String s)方法去数据库查询用户
            @Override
            public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
                return new UserDetails() {
                    @Override
                    public Collection<? extends GrantedAuthority> getAuthorities() {
                        return null;
                    }

                    @Override
                    public String getPassword() {
                        return "itxsl";
                    }

                    @Override
                    public String getUsername() {
                        return "itxsl";
                    }

                    @Override
                    public boolean isAccountNonExpired() {
                        return true;
                    }

                    @Override
                    public boolean isAccountNonLocked() {
                        return true;
                    }

                    @Override
                    public boolean isCredentialsNonExpired() {
                        return true;
                    }

                    @Override
                    public boolean isEnabled() {
                        return true;
                    }
                };
            }
        }     ;
    }



    @Bean//密码编码模式,这里没使用加密,需要加密可创建一个new BCryptPasswordEncoder()返回,
    // 这里加密后,用户密码和ClientSecret都会用加密后的串进行校验密码
    public PasswordEncoder passwordEncoder(){
        
        return  new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return charSequence.toString().equals(s);
            }
        };
    }

    @Override
    @Bean//定义没有password grant_type
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

5.创建一个配置文件application.yml配置端口,内容如下:
server:
  port: 7002
logging:
  level:
    root: info

二.启动项目测试认证服务中心。

1.启动项目

在这里插入图片描述

项目启动成功!

2.根据第三方应用配置中心及用户配置中心中应用信息和用户信息进行测试。
3.在浏览器地址栏中输入下面内容并访问:

在这里插入图片描述

http://127.0.0.1:7002/oauth/authorize?client_id=itxsl&redirect_uri=http://localhost:7003/auth/account&response_type=code&scope=all&state=1a6L30

接下来会进入一个登录页面:

在这里插入图片描述

4.输入账号和密码‘itxsl’完成登录拿到code码:

在这里插入图片描述

5.接下来打开postman,使用post请求获取token:

输入client_id和client_sercet
在这里插入图片描述

扫描二维码关注公众号,回复: 6020656 查看本文章

成功获取access_token等信息:

到此认证服务器Demo搭建完毕。

源码地址: 源码

猜你喜欢

转载自blog.csdn.net/xslde_com/article/details/89531037