java spring oauth2.0_spring-security oauth2.0简单集成

需要2个服务,一个认证授权服务,一个资源服务

认证授权服务为客户端颁发令牌,资源服务用于客户端获取用户信息。

1. 总体架构:

ffc49c45fa9cfa80f2d9229d87b5886a.png

2.认证授权服务

pom文件:

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.2.6.RELEASE

com.intfish

auth-server

0.0.1-SNAPSHOT

auth-server

Demo project for Spring Boot

UTF-8

UTF-8

1.8

Hoxton.SR3

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-aop

org.springframework.boot

spring-boot-devtools

runtime

true

org.projectlombok

lombok

true

org.springframework.cloud

spring-cloud-starter-oauth2

org.springframework.cloud

spring-cloud-starter-security

org.springframework.boot

spring-boot-starter-test

test

org.junit.vintage

junit-vintage-engine

org.springframework.cloud

spring-cloud-dependencies

${spring-cloud.version}

pom

import

org.springframework.boot

spring-boot-maven-plugin

2.1 项目目录:

013989c250d92ba5501fb179a4c6af87.png

2.2 代码

AuthorizationConfig.java

packagecom.intfish.authorization.config;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.security.authentication.AuthenticationManager;importorg.springframework.security.core.userdetails.UserDetailsService;importorg.springframework.security.crypto.factory.PasswordEncoderFactories;importorg.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;importorg.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;importorg.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;importorg.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;importorg.springframework.security.oauth2.provider.token.TokenStore;importorg.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

@Configurationpublic class AuthorizationConfig extendsAuthorizationServerConfigurerAdapter {

@AutowiredprivateAuthenticationManager authenticationManager;

@AutowiredprivateUserDetailsService userDetailsService;

@BeanpublicTokenStore memoryTokenStore(){//token存在内存中

return newInMemoryTokenStore();

}

@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) throwsException {//tokenKeyAccess("permitAll()")表示谁都可以获取令牌 checkTokenAccess("isAuthenticated()")表示只有认证之后才可以检查令牌

security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()").allowFormAuthenticationForClients();

}

@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throwsException {

clients.inMemory().withClient("client1") //客户端id

.authorizedGrantTypes("authorization_code", "refresh_token") //允许authorization_code和refresh_token授权

.scopes("test") //权限范围 可以是 read,write 自己填

.secret(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("123456")) //客户端secret

.redirectUris("http://www.baidu.com"); //回调地址,用于接收code和access_token

}

@Override

public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

endpoints

.authenticationManager(authenticationManager)

// .tokenServices(tokenService())

.tokenStore(tokenStore())

.userDetailsService(userDetailsService);

}

@Bean

public DefaultTokenServices tokenService() {

DefaultTokenServices tokenServices = new DefaultTokenServices();

//配置token存储

tokenServices.setTokenStore(tokenStore());

//开启支持refresh_token,此处如果之前没有配置,启动服务后再配置重启服务,可能会导致不返回token的问题,解决方式:清除redis对应token存储

tokenServices.setSupportRefreshToken(true);

//复用refresh_token

tokenServices.setReuseRefreshToken(true);

//token有效期,设置12小时

tokenServices.setAccessTokenValiditySeconds(12 * 60 * 60);

//refresh_token有效期,设置一周

tokenServices.setRefreshTokenValiditySeconds(7 * 24 * 60 * 60);

return tokenServices;

}

}

SecurityConfig.java

packagecom.intfish.authorization.config;importorg.springframework.context.annotation.Bean;importorg.springframework.security.authentication.AuthenticationManager;importorg.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;importorg.springframework.security.config.annotation.web.configuration.EnableWebSecurity;importorg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;importorg.springframework.security.core.userdetails.User;importorg.springframework.security.core.userdetails.UserDetailsService;importorg.springframework.security.crypto.factory.PasswordEncoderFactories;importorg.springframework.security.provisioning.InMemoryUserDetailsManager;

@EnableWebSecuritypublic class SecurityConfig extendsWebSecurityConfigurerAdapter {

@Bean

@Overridepublic AuthenticationManager authenticationManagerBean() throwsException {return super.authenticationManagerBean();

}

@Bean

@OverridepublicUserDetailsService userDetailsService() {//基于内存查询用户

InMemoryUserDetailsManager userDetailsManager = newInMemoryUserDetailsManager();

userDetailsManager.createUser(

User.withUsername("admin")

.password(

PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("admin")

).authorities("USER").build()

);returnuserDetailsManager;

}

@Overridepublic void configure(AuthenticationManagerBuilder auth) throwsException {

auth.userDetailsService(userDetailsService());

}

}

启动类 AuthServerApplication.java

packagecom.intfish.authorization;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;

@SpringBootApplication

@EnableAuthorizationServer//启用认证授权服务

public classAuthServerApplication {public static voidmain(String[] args) {

SpringApplication.run(AuthServerApplication.class, args);

}

}

配置文件 application.properties

//默认配置即可 什么都不用配置

到此认证授权服务配置完成,直接启动即可。

3. 资源服务(用于根据access_token查询用户信息)

pom文件

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.2.6.RELEASE

com.intfish

resource-server

0.0.1-SNAPSHOT

resource-server

Demo project for Spring Boot

UTF-8

UTF-8

1.8

Hoxton.SR3

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-aop

org.springframework.boot

spring-boot-devtools

runtime

true

org.projectlombok

lombok

true

org.springframework.boot

spring-boot-starter-test

test

org.springframework.cloud

spring-cloud-starter-oauth2

org.springframework.cloud

spring-cloud-starter-security

com.alibaba

fastjson

1.2.62

org.springframework.cloud

spring-cloud-dependencies

${spring-cloud.version}

pom

import

org.springframework.boot

spring-boot-maven-plugin

3.1 资源服务项目目录

96e59e4c46be4453bcb6eeda62f70cfd.png

3.2 代码

UserController.java

packagecom.intfish.resourceserver.controller;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.security.core.Authentication;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;

@RestController

@RequestMapping("/user")public classUserController {private Logger log = LoggerFactory.getLogger(this.getClass());

@PostMapping("getUserInfo")publicObject getUserInfo(Authentication authentication){

log.info("获取用户信息;"+authentication);returnauthentication;

}

}

启动类 ResourceServerApplication.java

packagecom.intfish.resourceserver;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;

@SpringBootApplication

@EnableResourceServer//开启资源服务

public classResourceServerApplication {public static voidmain(String[] args) {

SpringApplication.run(ResourceServerApplication.class, args);

}

}

配置文件 application.properties

server.port=9090auth-server-url=http://localhost:8080

security.oauth2.client.client-id=client1

security.oauth2.client.client-secret=123456security.oauth2.client.scope=test

security.oauth2.client.access-token-uri=${auth-server-url}/oauth/token

security.oauth2.client.user-authorization-uri=${auth-server-url}/oauth/authorize

security.oauth2.resource.token-info-uri=${auth-server-url}/oauth/check_token

到此资源服务配置完成,启动服务即可。

4. 认证授权+获取令牌(access_token)

4.1 用浏览器访问 认证授权服务

http://localhost:8080/oauth/authorize?response_type=code&client_id=client1&redirect_uri=http://www.baidu.com

然后自动跳入登录地址,输入账号密码登录: admin/admin

66a10497208174cf6227538061fa01b9.png

登录成功提示用户是否允许授权,点Approve允许

6ff074fd178a1998b92fcd10e5a05412.png

登录成功,自动调转到回调地址,并在url中带有code参数

ef7ad9b72510234f6615deb3f52ab93b.png

那着这个code用postman发请求获取令牌

e4a5581d1826c2109fa653021007df78.png

成功拿到令牌access_token。

接着用这个令牌访问资源服务

8da87debad3ebcc480de4c5920cd8da7.png

请求成功。也可以这样请求

http://localhost:9090/user/getUserInfo?access_token=2f3c1803-dbb8-4f95-acf6-88a298309ecd

到此全部结束。!!!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值