美文网首页
搭建oauth2.0 授权服务器

搭建oauth2.0 授权服务器

作者: G先生_海林 | 来源:发表于2020-11-12 23:27 被阅读0次

    pom.xml

    <?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">
        <modelVersion>4.0.0</modelVersion>
        <groupId>io.spring2go</groupId>
        <artifactId>authcode-server</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>authcode-server</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.10.RELEASE</version>
            <relativePath /> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <!-- for OAuth 2.0 -->
            <dependency>
                <groupId>org.springframework.security.oauth</groupId>
                <artifactId>spring-security-oauth2</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    
    </project>
    
    
    

    配置授权服务器

    package io.spring2go.authcodeserver.config;
    
    import org.springframework.context.annotation.Configuration;
    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;
    
    //授权服务器配置
    @Configuration
    @EnableAuthorizationServer
    public class OAuth2AuthorizationServer extends
            AuthorizationServerConfigurerAdapter {
    
        @Override
        public void configure(ClientDetailsServiceConfigurer clients)
                throws Exception {
            clients.inMemory()
                .withClient("clientapp")
                .secret("112233")
                .redirectUris("http://localhost:9001/callback")
                // 授权码模式
                .authorizedGrantTypes("authorization_code")
                .scopes("read_userinfo", "read_contacts");
        }
    
    }
    
    

    配置资源服务器

    package io.spring2go.authcodeserver.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
    import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
    
    //资源服务配置
    @Configuration
    @EnableResourceServer
    public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter {
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                .anyRequest()
                .authenticated()
            .and()
                .requestMatchers()
                .antMatchers("/api/**");
        }
    
    }
    
    

    编写资源api

    package io.spring2go.authcodeserver.api;
    
    import org.springframework.http.ResponseEntity;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.security.core.userdetails.User;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class UserController {
    
        // 资源API
        @RequestMapping("/api/userinfo")
        public ResponseEntity<UserInfo> getUserInfo() {
            User user = (User) SecurityContextHolder.getContext()
                    .getAuthentication().getPrincipal();
            String email = user.getUsername() + "@spring2go.com";
    
            UserInfo userInfo = new UserInfo();
            userInfo.setName(user.getUsername());
            userInfo.setEmail(email);
    
            return ResponseEntity.ok(userInfo);
        }
    
    }
    
    public class UserInfo {
    
        private String name;
    
        private String email;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    
    }
    
    

    启动类

    package io.spring2go.authcodeserver;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class AuthCodeServerApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(AuthCodeServerApplication.class, args);
        }
    }
    
    

    readme

    基于授权码模式+Spring Security OAuth2的最简授权服务器

    操作方式

    1. 获取授权码

    浏览器请求:

    http://localhost:8080/oauth/authorize?client_id=clientapp&redirect_uri=http://localhost:9001/callback&response_type=code&scope=read_userinfo

    注意:state参数暂忽略

    响应案例:

    http://localhost:9001/callback?code=8uYpdo

    #2. 获取访问令牌

    curl -X POST --user clientapp:112233 http://localhost:8080/oauth/token -H
    "content-type: application/x-www-form-urlencoded" -d
    "code=8uYpdo&grant_type=authorization_code&redirect_uri=http%3A%2F%2Flocalh
    ost%3A9001%2Fcallback&scope=read_userinfo"

    image.png

    案例响应:

    {
        "access_token": "3e7279ef-0453-4356-8104-579503e38a3e",
        "token_type": "bearer",
        "expires_in": 43199,
        "scope": "read_userinfo"
    }
    

    3. 调用API

    image.png

    curl -X GET http://localhost:8080/api/userinfo -H "authorization: Bearer 36cded80-b6f5-43b7-bdfc-594788a24530"

    案例响应:

    {
        "name": "bobo",
        "email": "bobo@spring2go.com"
    }
    

    这样简单授权服务器就搭建成功了

    相关文章

      网友评论

          本文标题:搭建oauth2.0 授权服务器

          本文链接:https://www.haomeiwen.com/subject/lmmmbktx.html