Spring boot security oauth2.0,仅5个文件,完成4种授权模式,再跑不通学不会来砍我!!

不多逼逼,直接开始,文章下面有可以直接运行的demo

一、授权服务器代码

共三个类

package com.cjs.sso.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
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;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    // accessToken有效期
    private static int ACCESS_TOKEN_VALIDITY_SECONDS = 7200;

    // refreshToken有效期
    private static int REFRESH_TOKEN_VALIDITY_SECONDS = 7200;

    @Autowired
    private MyAuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().                                                          //使用内存
                withClient("elapse").                                      //客户端ID
                secret(new BCryptPasswordEncoder().encode("123456"))    //客户端密码
                .redirectUris("https://www.baidu.com")                               //重定向地址
                .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token", "password", "implicit")  //开放四种模式
                .scopes("all")
                .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
                .refreshTokenValiditySeconds(REFRESH_TOKEN_VALIDITY_SECONDS);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager).allowedTokenEndpointRequestMethods(HttpMethod.GET,
                HttpMethod.POST);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()").checkTokenAccess("permitAll()").allowFormAuthenticationForClients();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder;
    }
}
package com.cjs.sso.config;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.stereotype.Component;

@Component
public class MyAuthenticationManager implements AuthenticationManager {

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        UserDetailsService userDetailsService = new InMemoryUserDetailsManager();
        ((InMemoryUserDetailsManager) userDetailsService).createUser(User.withUsername("user")
                .password(new BCryptPasswordEncoder().encode("123456")).authorities("ROLE_USER").build());

        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
        return daoAuthenticationProvider.authenticate(authentication);
    }

}
package com.cjs.sso.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("user")
                .password(new BCryptPasswordEncoder().encode("123456")).authorities("ROLE");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().formLogin();
    }
}

二、资源服务器

共两个类

package com.cjs.example.config;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/order")
public class OrderController {
    @RequestMapping("/getOrder")
    public String getOrder() {
        return "i am order resource";
    }
}
package com.cjs.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 对 api/order 请求进行拦截
        http.authorizeRequests().antMatchers("/api/order/**").authenticated();
    }
}

三、测试四种模式方法,(我都嘴对嘴教你了)

.授权码模式(需要先登陆获取授权码,再获取access_token)
1.获取code()
http://localhost:8080/oauth/authorize?response_type=code&client_id=elapse&redirect_uri=https://www.baidu.com
2.通过code获取access_token
http://localhost:8080/oauth/token?grant_type=authorization_code&code=keLf84&redirect_uri=https://www.baidu.com&client_id=elapse&client_secret=123456&scope=all


二.密码模式(发送账户密码,敏感信息暴露)
http://localhost:8080/oauth/token?client_id=elapse&client_secret=123456&grant_type=password&username=user&password=123456


三、客户端模式(最不安全,只要知道id和口令就可以获取access_token)
http://localhost:8080/oauth/token?client_id=elapse&client_secret=123456&grant_type=client_credentials

四、简化模式(与授权码一样,但无需code)
http://localhost:8080/oauth/authorize?client_id=elapse&response_type=token&scope=all&redirect_uri=https://www.baidu.com

四、访问资源服务器

任选一种模式,用浏览器输入地址,然后拿到access_token,用postman去访问资源服务器
http://localhost:8081/api/order/getOrder

在这里插入图片描述

在这里插入图片描述

没问题了吧?
还不会?得了,demo直接给你

五、DEMO下载

【demo下载】

相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页