今天就跟大家聊聊有關(guān)Spring Cloud中怎么利用OAUTH2實(shí)現(xiàn)認(rèn)證授權(quán),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
永定ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書未來(lái)市場(chǎng)廣闊!成為成都創(chuàng)新互聯(lián)公司的ssl證書銷售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:028-86922220(備注:SSL證書合作)期待與您的合作!OAUTH2中的角色:
Resource Server
:被授權(quán)訪問(wèn)的資源
Authotization Server
:OAUTH2認(rèn)證授權(quán)中心
Resource Owner
: 用戶
Client
:使用API的客戶端(如Android 、IOS、web app)
Grant Type:
Authorization Code
:用在服務(wù)端應(yīng)用之間
Implicit
:用在移動(dòng)app或者web app(這些app是在用戶的設(shè)備上的,如在手機(jī)上調(diào)起微信來(lái)進(jìn)行認(rèn)證授權(quán))
Resource Owner Password Credentials(password)
:應(yīng)用直接都是受信任的(都是由一家公司開(kāi)發(fā)的,本例子使用
Client Credentials
:用在應(yīng)用API訪問(wèn)。
1.基礎(chǔ)環(huán)境
使用Postgres
作為賬戶存儲(chǔ),Redis
作為Token
存儲(chǔ),使用docker-compose
在服務(wù)器上啟動(dòng)Postgres
和Redis
。
Redis: image: sameersbn/redis:latest ports: - "6379:6379" volumes: - /srv/docker/redis:/var/lib/redis:Z restart: always PostgreSQL: restart: always image: sameersbn/postgresql:9.6-2 ports: - "5432:5432" environment: - DEBUG=false - DB_USER=wang - DB_PASS=yunfei - DB_NAME=order volumes: - /srv/docker/postgresql:/var/lib/postgresql:Z
2.auth-server
2.1 OAuth3服務(wù)配置
Redis
用來(lái)存儲(chǔ)token
,服務(wù)重啟后,無(wú)需重新獲取token
.
@Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private RedisConnectionFactory connectionFactory; @Bean public RedisTokenStore tokenStore() { return new RedisTokenStore(connectionFactory); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .authenticationManager(authenticationManager) .tokenStore(tokenStore()); } @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security .tokenKeyAccess("permitAll()") .checkTokenAccess("isAuthenticated()"); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("android") .scopes("xx") //此處的scopes是無(wú)用的,可以隨意設(shè)置 .secret("android") .authorizedGrantTypes("password", "authorization_code", "refresh_token") .and() .withClient("webapp") .scopes("xx") .authorizedGrantTypes("implicit"); } }
2.2 Resource服務(wù)配置
auth-server
提供user信息,所以auth-server
也是一個(gè)Resource Server
@Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http .csrf().disable() .exceptionHandling() .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED)) .and() .authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); } }
@RestController public class UserController { @GetMapping("/user") public Principal user(Principal user){ return user; } }
2.3 安全配置
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public UserDetailsService userDetailsService(){ return new DomainUserDetailsService(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(userDetailsService()) .passwordEncoder(passwordEncoder()); } @Bean public SecurityEvaluationContextExtension securityEvaluationContextExtension() { return new SecurityEvaluationContextExtension(); } //不定義沒(méi)有password grant_type @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
2.4 權(quán)限設(shè)計(jì)
采用用戶(SysUser)
角色(SysRole)
權(quán)限(SysAuthotity)
設(shè)置,彼此之間的關(guān)系是多對(duì)多
。通過(guò)DomainUserDetailsService
加載用戶和權(quán)限。
2.5 配置
spring: profiles: active: ${SPRING_PROFILES_ACTIVE:dev} application: name: auth-server jpa: open-in-view: true database: POSTGRESQL show-sql: true hibernate: ddl-auto: update datasource: platform: postgres url: jdbc:postgresql://192.168.1.140:5432/auth username: wang password: yunfei driver-class-name: org.postgresql.Driver redis: host: 192.168.1.140 server: port: 9999 eureka: client: serviceUrl: defaultZone: http://${eureka.host:localhost}:${eureka.port:8761}/eureka/ logging.level.org.springframework.security: DEBUG logging.leve.org.springframework: DEBUG ##很重要 security: oauth3: resource: filter-order: 3
2.6 測(cè)試數(shù)據(jù)
data.sql
里初始化了兩個(gè)用戶admin
->ROLE_ADMIN
->query_demo
,wyf
->ROLE_USER
3.order-service
3.1 Resource服務(wù)配置
@Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter{ @Override public void configure(HttpSecurity http) throws Exception { http .csrf().disable() .exceptionHandling() .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED)) .and() .authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); } }
3.2 用戶信息配置
order-service
是一個(gè)簡(jiǎn)單的微服務(wù),使用auth-server
進(jìn)行認(rèn)證授權(quán),在它的配置文件指定用戶信息在auth-server
的地址即可:
security: oauth3: resource: id: order-service user-info-uri: http://localhost:8080/uaa/user prefer-token-info: false
3.3 權(quán)限測(cè)試控制器
具備authority
未query-demo
的才能訪問(wèn),即為admin
用戶
@RestController public class DemoController { @GetMapping("/demo") @PreAuthorize("hasAuthority('query-demo')") public String getDemo(){ return "good"; } }
4 api-gateway
api-gateway
在本例中有2個(gè)作用:
本身作為一個(gè)client,使用implicit
作為外部app訪問(wèn)的方向代理
4.1 關(guān)閉csrf并開(kāi)啟Oauth3 client支持
@Configuration @EnableOAuth3Sso public class SecurityConfig extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); } }
4.2 配置
zuul: routes: uaa: path: /uaa/** sensitiveHeaders: serviceId: auth-server order: path: /order/** sensitiveHeaders: serviceId: order-service add-proxy-headers: true security: oauth3: client: access-token-uri: http://localhost:8080/uaa/oauth/token user-authorization-uri: http://localhost:8080/uaa/oauth/authorize client-id: webapp resource: user-info-uri: http://localhost:8080/uaa/user prefer-token-info: false
5 演示
5.1 客戶端調(diào)用
使用Postman
向http://localhost:8080/uaa/oauth/token
發(fā)送請(qǐng)求獲得access_token
(admin用戶的如7f9b54d4-fd25-4a2c-a848-ddf8f119230b
)
admin用戶
wyf用戶
看完上述內(nèi)容,你們對(duì)Spring Cloud中怎么利用OAUTH2實(shí)現(xiàn)認(rèn)證授權(quán)有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。
網(wǎng)頁(yè)名稱:SpringCloud中怎么利用OAUTH2實(shí)現(xiàn)認(rèn)證授權(quán)-創(chuàng)新互聯(lián)
路徑分享:http://jinyejixie.com/article44/ccpjee.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開(kāi)發(fā)、小程序開(kāi)發(fā)、品牌網(wǎng)站建設(shè)、定制開(kāi)發(fā)、微信公眾號(hào)、外貿(mào)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容