Implementation example of authorization based on oau22.
InSpring Cloud
Need to useOAUTH2
To implement uniform authentication and authorization for multiple microservices.OAUTH Service
Send a typegrant type
Perform centralized authentication and authorization to obtainaccess_token
And this token is trusted by other microservices. We canaccess_token
To implement uniform authentication and authorization for microservices.
This example provides four parts:
discovery-service
: Basic module of Service Registration and Discovery
auth-server
: Oau2authentication and authorization center
order-service
: Common microservice, used for authentication and authorization
api-gateway
: Border Gateway (all microservices are behind it)
Role in oau22:
Resource Server
: Authorized Resource
Authotization Server
: Oau2authentication and authorization center
Resource Owner
: User
Client
: API clients (such as Android, IOS, and web apps)
Grant Type:
Authorization Code
: Used between server applications
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)
Resource Owner Password Credentials(password)
: Applications are directly trusted (all developed by a company. This example uses
Client Credentials
: Used for application API access.
1. Basic Environment
UsePostgres
Stored as an account,Redis
AsToken
Storage, usedocker-compose
Start on the serverPostgres
AndRedis
.
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
Redis
Used for storagetoken
After 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-server
Provide user information, soauth-server
It 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
. PassDomainUserDetailsService
Attach 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.sql
Two 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-service
Is a simple microservice, usingauth-server
Perform authentication and authorization. In its configuration file, specify the user information inauth-server
Address:
security: oauth2: resource: id: order-service user-info-uri: http://localhost:8080/uaa/user prefer-token-info: false
3.3 permission test Controller
Yesauthority
Weiquery-demo
Can be accessed, that isadmin
User
@RestControllerpublic class DemoController { @GetMapping("/demo") @PreAuthorize("hasAuthority('query-demo')") public String getDemo(){ return "good"; }}
4 api-gateway
api-gateway
This example has two functions:
- As a client, use
implicit
- 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
UsePostman
Directionhttp://localhost:8080/uaa/oauth/token
Send 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.