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下载】

<p> <span style="color:#337fe5;"><strong> </strong></span> </p> <p class="MsoNormal"> <span style="color:#000000;font-size:16px;">本课程总计13大章节,115课时,是一门全面的SpringCloud微服务体系化课程。课程共包括</span><span style="color:#000000;font-size:16px;">十三个大章节,涵盖注册中心、网关、熔断、降级、监控、安全、限流等全部体系。</span><span style="color:#000000;font-size:16px;">包含阿里巴巴Nacos,Consul,Spring Cloud Gateway,OAuth2.0 JWT 等主流技术。</span> </p> <p class="MsoNormal"> <span style="color:#000000;font-size:16px;"> </span> </p> <p>   </p> <p> <span style="color:#337fe5;"><strong>[为什么要Spring Cloud微服务]</strong></span> </p> <p> <span style="color:#4d555d;"> </span> </p> <p class="ql-long-24357476" style="font-family:"color:#222226;font-size:14px;background-color:#ffffff;"> <span style="font-family:"background-color:#FFFFFF;"><span style="font-size:12px;">SpringCloud作为主流微服务框架,</span><span style="color:#4d555d;font-family:"background-color:#FFFFFF;font-size:12px;">已成为各互联网公司的首选框架,国内外企业占有率持续攀升,</span><span style="font-size:12px;">是Java工程师的必备技能。</span></span><span style="font-family:"background-color:#FFFFFF;font-size:12px;">就连大名鼎鼎的阿里巴巴</span><span style="font-family:"background-color:#FFFFFF;font-size:12px;">dubbo</span><span style="font-family:"background-color:#FFFFFF;font-size:12px;">也正式更名为</span><span style="font-family:"background-color:#FFFFFF;font-size:12px;">Spring Cloud Alibaba</span><span style="font-family:"background-color:#FFFFFF;font-size:12px;">,成为了</span><span style="font-family:"background-color:#FFFFFF;font-size:12px;">Spring Cloud </span><span style="font-family:"background-color:#FFFFFF;font-size:12px;">微服务中的一个子模块。</span><span style="font-family:"background-color:#FFFFFF;font-size:12px;">Spring Cloud是企业架构转型、个人能力提升、架构师进阶的不二选择。</span><span style="font-family:"background-color:#FFFFFF;"> </span> </p> <p class="ql-long-8780922" style="font-size:11pt;color:#494949;">   </p> <p class="ql-long-8780922" style="font-size:11pt;color:#494949;">   </p> <p class="ql-long-24357476" style="font-family:"color:#222226;font-size:14px;background-color:#ffffff;"> <span style="color:#337fe5;"><strong>【推荐你习这门课的理由:<span style="color:#e53333;">知识体系完整+丰富习资料】</span></strong></span> </p> <p class="ql-long-24357476" style="font-family:"color:#222226;font-size:14px;background-color:#ffffff;">   </p> <p class="MsoNormal"> 1、本课程总计13大章节,115课时,是一门全面的SpringCloud微服务体系化课程。 </p> <p class="MsoNormal"> 2、课程0基础入门,逐层递进深入,理论和代码相结合。 </p> <p class="MsoNormal"> 3、十三个大章节,涵盖注册中心、网关、熔断、降级、监控、安全、限流等全部体系。 </p> <p class="MsoNormal"> 4、包含阿里巴巴Nacos,Consul,Spring Cloud Gateway,OAuth2.0 JWT 主流技术。 </p> <p style="background:white;"> 5、课程附带230页高清PDF正版课件、Hoxton版本配套项目源码37个、Edgware版本配套项目26个,所有代码均有详细注释。 </p> <p>   </p> <p class="MsoNormal">   </p> <p> <span style="color:#337fe5;">【主讲讲师】</span> </p> <p> <span style="color:#337fe5;"><span style="color:#000000;">尹洪亮Kevin:</span><br /> <span style="color:#000000;">现任职某互联网公司首席架构师,负责系统架构、项目群管理、产品研发工作。</span><br /> <span style="color:#000000;">10余年软件行业经验,具有数百个线上项目实战经验。</span><br /> <span style="color:#000000;">擅长JAVA技术栈、高并发高可用伸缩式微服务架构、DevOps。</span><br /> <span style="color:#000000;">主导研发的蜂巢微服务架构已经成功支撑数百个微服务稳定运行</span></span> </p> <p> <span style="color:#337fe5;"><span style="color:#000000;"> </span></span> </p> <p>   </p> <p class="ql-long-24357476" style="font-family:"color:#222226;font-size:14px;background-color:#ffffff;"> <span style="color:#337fe5;"><strong>【完后我将达到什么水平?】</strong></span> </p> <p class="MsoNoSpacing" style="margin-left:18.0pt;text-indent:-18.0pt;"> 1、 对Spring Cloud的各个组件能够熟练配置、开发、部署。 </p> <p class="MsoNoSpacing" style="margin-left:18.0pt;text-indent:-18.0pt;"> 2、 吊打一切关于Spring Cloud微服务的笔试面试题 </p> <p class="MsoNoSpacing" style="margin-left:18.0pt;text-indent:-18.0pt;"> 3、 能够上手搭建十分完整的微服务分布式系统,涵盖服务注册与发现、负载、网关、配置中心、监控、安全、熔断等。 </p> <p class="MsoNoSpacing" style="margin-left:18.0pt;text-indent:-18.0pt;"> 4、 对整个微服务体系架构有十分清晰准确的掌握。 </p> <p>   </p> <p class="ql-long-24357476"> <span style="font-family:""> </span> </p> <p class="MsoListParagraph" style="margin-left:36pt;text-indent:-36pt;" align="left"> <strong><span style="color:#337fe5;">【</span><span style="color:#337fe5;">面向人群</span><span style="color:#337fe5;">】</span></strong> </p> <p class="MsoListParagraph" style="margin-left:18.0pt;text-indent:-18.0pt;"> 1、 <span style="color:#4d555d;">不了解微服务是什么,</span>感觉微服务很难、不敢,<span style="color:#4d555d;">网上资料松散,</span>没有好的习资料 </p> <p class="MsoListParagraph" style="margin-left:18.0pt;text-indent:-18.0pt;"> 2、 这么多年还一直在写SSH、SSM项目,没有更新过自己的知识体系。 </p> <p class="MsoListParagraph" style="margin-left:18.0pt;text-indent:-18.0pt;"> 3、 Spring Cloud组件太多,不知道应该重点关注和习哪些。 </p> <p class="MsoListParagraph" style="margin-left:18.0pt;text-indent:-18.0pt;"> 4不会搭建微服务项目、依赖项目太多、完全搞不清楚。 </p> <p class="MsoListParagraph" style="margin-left:18.0pt;text-indent:-18.0pt;">   </p> <p class="MsoListParagraph" style="margin-left:18.0pt;text-indent:-18.0pt;"> <span style="color:#337fe5;"><strong>【课程知识体系图】</strong></span> </p> <p class="MsoListParagraph" style="margin-left:18.0pt;text-indent:-18.0pt;"> <span style="color:#337fe5;"><strong><img src="https://img-bss.csdnimg.cn/202007100719132383.png" alt="" /><br /> </strong></span> </p>
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页