Implementation example of authorization based on oau22.

Source: Internet
Author: User
Tags oauth

Implementation example of authorization based on oau22.

InSpring CloudNeed to useOAUTH2To implement uniform authentication and authorization for multiple microservices.OAUTH ServiceSend a typegrant typePerform centralized authentication and authorization to obtainaccess_tokenAnd this token is trusted by other microservices. We canaccess_tokenTo implement uniform authentication and authorization for microservices.

This example provides four parts:

  1. discovery-service: Basic module of Service Registration and Discovery
  2. auth-server: Oau2authentication and authorization center
  3. order-service: Common microservice, used for authentication and authorization
  4. api-gateway: Border Gateway (all microservices are behind it)

Role in oau22:

  1. Resource Server: Authorized Resource
  2. Authotization Server: Oau2authentication and authorization center
  3. Resource Owner: User
  4. Client: API clients (such as Android, IOS, and web apps)

Grant Type:

  1. Authorization Code: Used between server applications
  2. Implicit: Used in mobile apps or web apps (these apps are on users' devices, for example, they are upgraded on mobile phones for authentication and authorization)
  3. Resource Owner Password Credentials(password): Applications are directly trusted (all developed by a company. This example uses
  4. Client Credentials: Used for application API access.

1. Basic Environment

UsePostgresStored as an account,RedisAsTokenStorage, usedocker-composeStart on the serverPostgresAndRedis.

Redis: image: sameersbn/redis:latest ports: - "6379:6379" volumes: - /srv/docker/redis:/var/lib/redis:Z restart: alwaysPostgreSQL: 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 oau2service Configuration

RedisUsed for storagetokenAfter the service is restarted, you do not need to obtain it again.token.

@ Configuration @ your class AuthorizationServerConfig extends {@ Autowired private AuthenticationManager authenticationManager; @ Autowired private RedisConnectionFactory connectionFactory; @ Bean public redi#enstore tokenStore () {return new redi#enstore (connectionFactory );} @ Override public void configure (AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints. authenticationManager (authenticationManager ). tokenStore () ;}@ Override public void configure (authorizationserversecuritypolicer security) throws Exception {security. tokenKeyAccess ("permitAll ()"). checkTokenAccess ("isAuthenticated ()") ;}@ Override public void configure (clientdetailsservicepolicer clients) throws Exception {clients. inMemory (). withClient ("android "). scopes ("xx") // scopes here are useless and can be set at will. secret ("android "). authorizedGrantTypes ("password", "authorization_code", "refresh_token "). and (). withClient ("webapp "). scopes ("xx "). authorizedGrantTypes ("implicit ");}}

2.2 Resource Service Configuration

auth-serverProvide user information, soauth-serverIt is alsoResource Server

@Configuration@EnableResourceServerpublic 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(); }}
@RestControllerpublic class UserController { @GetMapping("/user") public Principal user(Principal user){  return user; }}

2.3 Security Configuration

@ Configurationpublic class SecurityConfig extends websecurityjavaseradapter {@ Bean public UserDetailsService userDetailsService () {return new DomainUserDetailsService ();} @ Bean public PasswordEncoder passwordEncoder () {return new response ();} @ Override protected void configure (AuthenticationManagerBuilder auth) throws Exception {auth. userDetailsService ()). passwordEncoder () ;}@ Bean public SecurityEvaluationContextExtension encode () {return new evaluate () ;}// no password grant_type @ Override @ Bean public AuthenticationManager authenticationManagerBean () is defined () throws Exception {return super. authenticationManagerBean ();}}

2.4 permission Design

UseUser (SysUser) Role (SysRole) Permission (SysAuthotity)Set, the relationship between them isMany-to-many. PassDomainUserDetailsServiceAttach users and permissions.

2.5 Configuration

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: S url: jdbc: postgresql: // 192.168.1.140: 5432/auth username: wang password: yunfei driver-class-name: org. postgresql. driver redis: host: 192.168.1.140server: port: 9999 eureka: client: serviceUrl: defaultZone: http: // $ {eureka. host: localhost }:: {eureka. port: 8761}/eureka/logging.level.org. springframework. security: DEBUGlogging.leve.org. springframework: DEBUG # Very important security: oauyy: resource: filter-order: 3

2.6 Test Data

data.sqlTwo users are initialized inadmin->ROLE_ADMIN->query_demo,wyf->ROLE_USER

3. order-service

3.1 Resource service configuration

@Configuration@EnableResourceServerpublic 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 user information configuration

order-serviceIs a simple microservice, usingauth-serverPerform authentication and authorization. In its configuration file, specify the user information inauth-serverAddress:

security: oauth2: resource:  id: order-service  user-info-uri: http://localhost:8080/uaa/user  prefer-token-info: false

3.3 permission test Controller

YesauthorityWeiquery-demoCan be accessed, that isadminUser

@RestControllerpublic class DemoController { @GetMapping("/demo") @PreAuthorize("hasAuthority('query-demo')") public String getDemo(){  return "good"; }}

4 api-gateway

api-gatewayThis example has two functions:

  1. As a client, useimplicit
  2. Acts as the proxy for external app access

4.1 disable csrf and enable oau2client support

@Configuration@EnableOAuth2Ssopublic class SecurityConfig extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception {  http.csrf().disable(); }}

4.2 Configuration

zuul: routes: uaa:  path: /uaa/**  sensitiveHeaders:  serviceId: auth-server order:  path: /order/**  sensitiveHeaders:  serviceId: order-service add-proxy-headers: truesecurity: oauth2: 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 demo

5.1 client call

UsePostmanDirectionhttp://localhost:8080/uaa/oauth/tokenSend request to getaccess_token(For example7f9b54d4-fd25-4a2c-a848-ddf8f119230b)

Admin user

Wyf user

5.2 webapp call in api-gateway

No tests are conducted for the time being.

6. Source Code address

Https://github.com/wiselyman/uaa-zuul

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.