springboot整合oauth2(二)

背景:在springboot整合oauth2(一)基础上进行,基于内存

一、创建项目

1. 在springboot-oauth2下创建一个子项目ram

二、认证服务配置

package com.zsx.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 AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //添加客户端信息
        // 使用in-memory存储客户端信息
        clients.inMemory()
                // client_id
                .withClient("clientId")
                // client_secret
                .secret("1234")
                // 该client允许的授权类型
                .authorizedGrantTypes("authorization_code")
                // 允许的授权范围
                .scopes("all").redirectUris("https://translate.google.cn");
    }
}

三、服务安全配置

package com.zsx.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic();
    }

}

 四、引导类

package com.zsx;

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

@SpringBootApplication
public class RAMApplication {

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

五、启动引导类

C:\software\jdk-11.0.3\bin\java.exe -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-javaagent:C:\software\JetBrains\IntelliJ IDEA 2019.1.3\lib\idea_rt.jar=11378:C:\software\JetBrains\IntelliJ IDEA 2019.1.3\bin" -Dfile.encoding=UTF-8 -classpath F:\IdeaProjects\springbootoauth2\ram\target\classes;C:\Users\zhang\.m2\repository\org\springframework\boot\spring-boot-starter-web\2.1.6.RELEASE\spring-boot-starter-web-2.1.6.RELEASE.jar;C:\Users\zhang\.m2\repository\org\springframework\boot\spring-boot-starter\2.1.6.RELEASE\spring-boot-starter-2.1.6.RELEASE.jar;C:\Users\zhang\.m2\repository\org\springframework\boot\spring-boot\2.1.6.RELEASE\spring-boot-2.1.6.RELEASE.jar;C:\Users\zhang\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.1.6.RELEASE\spring-boot-autoconfigure-2.1.6.RELEASE.jar;C:\Users\zhang\.m2\repository\org\springframework\boot\spring-boot-starter-logging\2.1.6.RELEASE\spring-boot-starter-logging-2.1.6.RELEASE.jar;C:\Users\zhang\.m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;C:\Users\zhang\.m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;C:\Users\zhang\.m2\repository\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;C:\Users\zhang\.m2\repository\org\apache\logging\log4j\log4j-to-slf4j\2.11.2\log4j-to-slf4j-2.11.2.jar;C:\Users\zhang\.m2\repository\org\apache\logging\log4j\log4j-api\2.11.2\log4j-api-2.11.2.jar;C:\Users\zhang\.m2\repository\org\slf4j\jul-to-slf4j\1.7.26\jul-to-slf4j-1.7.26.jar;C:\Users\zhang\.m2\repository\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;C:\Users\zhang\.m2\repository\org\yaml\snakeyaml\1.23\snakeyaml-1.23.jar;C:\Users\zhang\.m2\repository\org\springframework\boot\spring-boot-starter-json\2.1.6.RELEASE\spring-boot-starter-json-2.1.6.RELEASE.jar;C:\Users\zhang\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.9.9\jackson-databind-2.9.9.jar;C:\Users\zhang\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;C:\Users\zhang\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.9.9\jackson-core-2.9.9.jar;C:\Users\zhang\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.9\jackson-datatype-jdk8-2.9.9.jar;C:\Users\zhang\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.9\jackson-datatype-jsr310-2.9.9.jar;C:\Users\zhang\.m2\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.9\jackson-module-parameter-names-2.9.9.jar;C:\Users\zhang\.m2\repository\org\springframework\boot\spring-boot-starter-tomcat\2.1.6.RELEASE\spring-boot-starter-tomcat-2.1.6.RELEASE.jar;C:\Users\zhang\.m2\repository\org\apache\tomcat\embed\tomcat-embed-core\9.0.21\tomcat-embed-core-9.0.21.jar;C:\Users\zhang\.m2\repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.21\tomcat-embed-el-9.0.21.jar;C:\Users\zhang\.m2\repository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.21\tomcat-embed-websocket-9.0.21.jar;C:\Users\zhang\.m2\repository\org\hibernate\validator\hibernate-validator\6.0.17.Final\hibernate-validator-6.0.17.Final.jar;C:\Users\zhang\.m2\repository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;C:\Users\zhang\.m2\repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;C:\Users\zhang\.m2\repository\com\fasterxml\classmate\1.4.0\classmate-1.4.0.jar;C:\Users\zhang\.m2\repository\org\springframework\spring-web\5.1.8.RELEASE\spring-web-5.1.8.RELEASE.jar;C:\Users\zhang\.m2\repository\org\springframework\spring-webmvc\5.1.8.RELEASE\spring-webmvc-5.1.8.RELEASE.jar;C:\Users\zhang\.m2\repository\org\springframework\spring-aop\5.1.8.RELEASE\spring-aop-5.1.8.RELEASE.jar;C:\Users\zhang\.m2\repository\org\springframework\spring-expression\5.1.8.RELEASE\spring-expression-5.1.8.RELEASE.jar;C:\Users\zhang\.m2\repository\org\springframework\security\oauth\spring-security-oauth2\2.3.6.RELEASE\spring-security-oauth2-2.3.6.RELEASE.jar;C:\Users\zhang\.m2\repository\org\springframework\spring-beans\5.1.8.RELEASE\spring-beans-5.1.8.RELEASE.jar;C:\Users\zhang\.m2\repository\org\springframework\spring-core\5.1.8.RELEASE\spring-core-5.1.8.RELEASE.jar;C:\Users\zhang\.m2\repository\org\springframework\spring-jcl\5.1.8.RELEASE\spring-jcl-5.1.8.RELEASE.jar;C:\Users\zhang\.m2\repository\org\springframework\spring-context\5.1.8.RELEASE\spring-context-5.1.8.RELEASE.jar;C:\Users\zhang\.m2\repository\org\springframework\security\spring-security-core\5.1.5.RELEASE\spring-security-core-5.1.5.RELEASE.jar;C:\Users\zhang\.m2\repository\org\springframework\security\spring-security-config\5.1.5.RELEASE\spring-security-config-5.1.5.RELEASE.jar;C:\Users\zhang\.m2\repository\org\springframework\security\spring-security-web\5.1.5.RELEASE\spring-security-web-5.1.5.RELEASE.jar;C:\Users\zhang\.m2\repository\commons-codec\commons-codec\1.11\commons-codec-1.11.jar;C:\Users\zhang\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.13\jackson-mapper-asl-1.9.13.jar;C:\Users\zhang\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.13\jackson-core-asl-1.9.13.jar;C:\Users\zhang\.m2\repository\org\glassfish\jaxb\jaxb-core\2.3.0.1\jaxb-core-2.3.0.1.jar;C:\Users\zhang\.m2\repository\javax\xml\bind\jaxb-api\2.3.1\jaxb-api-2.3.1.jar;C:\Users\zhang\.m2\repository\javax\activation\javax.activation-api\1.2.0\javax.activation-api-1.2.0.jar;C:\Users\zhang\.m2\repository\org\glassfish\jaxb\txw2\2.3.1\txw2-2.3.1.jar;C:\Users\zhang\.m2\repository\com\sun\istack\istack-commons-runtime\3.0.5\istack-commons-runtime-3.0.5.jar;C:\Users\zhang\.m2\repository\com\sun\xml\bind\jaxb-impl\2.3.2\jaxb-impl-2.3.2.jar com.zsx.RAMApplication

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

2019-07-16 15:52:36.810  INFO 3128 --- [           main] com.zsx.RAMApplication                   : Starting RAMApplication on zsx with PID 3128 (F:\IdeaProjects\springbootoauth2\ram\target\classes started by zhang in F:\IdeaProjects\springbootoauth2)
2019-07-16 15:52:36.812  INFO 3128 --- [           main] com.zsx.RAMApplication                   : No active profile set, falling back to default profiles: default
2019-07-16 15:52:37.471  INFO 3128 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-07-16 15:52:37.488  INFO 3128 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-07-16 15:52:37.488  INFO 3128 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-07-16 15:52:37.538  INFO 3128 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-07-16 15:52:37.538  INFO 3128 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 702 ms
2019-07-16 15:52:37.751  INFO 3128 --- [           main] .s.s.UserDetailsServiceAutoConfiguration : 

Using generated security password: 11ef9ec0-3dbd-4be9-92e1-5b2cfea0b8c0

2019-07-16 15:52:37.780  INFO 3128 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/oauth/token'], Ant [pattern='/oauth/token_key'], Ant [pattern='/oauth/check_token']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@46e3559f, org.springframework.security.web.context.SecurityContextPersistenceFilter@f8a6243, org.springframework.security.web.header.HeaderWriterFilter@f29353f, org.springframework.security.web.authentication.logout.LogoutFilter@76e3b45b, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@45900b64, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@1727e03a, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@1da4b3f9, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@3b83459e, org.springframework.security.web.session.SessionManagementFilter@29be997f, org.springframework.security.web.access.ExceptionTranslationFilter@36aab105, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@52227eb2]
2019-07-16 15:52:37.783  INFO 3128 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@2d0b05, org.springframework.security.web.context.SecurityContextPersistenceFilter@4ed9f7b1, org.springframework.security.web.header.HeaderWriterFilter@47c7a9e5, org.springframework.security.web.csrf.CsrfFilter@64da6cbd, org.springframework.security.web.authentication.logout.LogoutFilter@20580d4e, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@21bd128b, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@2d119405, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@57e388c3, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@4b432e53, org.springframework.security.web.session.SessionManagementFilter@7951c3a2, org.springframework.security.web.access.ExceptionTranslationFilter@72a2312e]
2019-07-16 15:52:37.861  INFO 3128 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-16 15:52:37.963  INFO 3128 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-07-16 15:52:37.965  INFO 3128 --- [           main] com.zsx.RAMApplication                   : Started RAMApplication in 1.309 seconds (JVM running for 1.697)

 六、授权

1. 打开浏览器,输入请求http://localhost:8080/oauth/authorize?client_id=clientId&response_type=code

2. 通过账号密码登录 

3. 登录成功后,获取code 

4. 打开postman,通过code获取token 

5. 解决There is no PasswordEncoder mapped for the id \"null\" 

5.1 服务器安全配置修改为

package com.zsx.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        // 设置默认的加密方式
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
                // 在内存中创建用户并为密码加密
                .withUser("user").password(passwordEncoder().encode("1234")).roles("USER")
                .and()
                .withUser("admin").password(passwordEncoder().encode("1234")).roles("ADMIN");

    }
}

5.2 重新启动服务,重新获取code,再次获取token

6. 解决401 Unauthorized 

6.1 修改认证服务配置,给密码加密

package com.zsx.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
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 AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //添加客户端信息
        // 使用in-memory存储客户端信息
        clients.inMemory()
                // client_id
                .withClient("clientId")
                // client_secret
                .secret(passwordEncoder.encode("1234"))
                // 该client允许的授权类型
                .authorizedGrantTypes("authorization_code")
                // 允许的授权范围
                .scopes("all").redirectUris("https://translate.google.cn");
    }
}

6.2 重启服务,获取新的code,通过新code获取token 

 6.2 postman中添加Authorization参数

到此获取token成功

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值