spring oauth2 +springboot sso的案例分析

技术spring oauth2 +springboot sso的案例分析本篇内容主要讲解“spring oauth2 +springboot sso的案例分析”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性

本篇内容主要讲解"春天的羚羊单点登录(single sign-on的缩写)的案例分析",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"春天的羚羊单点登录(single sign-on的缩写)的案例分析"吧!

一、依赖

相关性

groupIdorg.springframework.security.oauth.boot/groupId

artifactIdspring-security-oauth 3-自动配置/artifactId

version2.1.6.RELEASE/version

/依赖性

二、服务端

1 .服务端需要的是授权与身份验证,通过配置@EnableAuthorizationServer 、@EnableWebSecurity 、@EnableResourceServer来完成配置。

2.先来配置网络安全的配置

打包。例子。oauth

导入组织。弹簧框架。靴子。自动配置。保安。安全属性;

导入组织。弹簧框架。语境。注释。豆子;

导入组织。弹簧框架。语境。注释。配置;

导入组织。弹簧框架。核心。注释。秩序;

导入组织。弹簧框架。保安。认证。authenticationmanager

导入组织。弹簧框架。保安。配置。BeanIds

导入组织。弹簧框架。保安。配置。注释。认证。建筑商。authenticationmanagerbuilder

导入组织。弹簧框架。保安。配置。注释。网络。建筑商。httpsecurity

导入组织。弹簧框架。保安。配置。注释。网络。建筑商。网络安全;

导入组织。弹簧框架。保安。配置。注释。网络。配置。enablewebsecurity

导入组织。弹簧框架。保安。配置。注释。网络。配置。websecurityconfiguradapter

导入组织。弹簧框架。保安。核心。用户详细信息。用户;

导入组织。弹簧框架。保安。核心。用户详细信息。用户详细信息服务;

导入组织。弹簧框架。保安。密码。b加密。bcryptpasswordencoder

导入组织。弹簧框架。保安。供应。在memoryuserdetailsmanager中;

/**

*@authorsorata

* @日期2019-07-2309:19

*/

@配置

@EnableWebSecurity

@Order(SecurityProperties .BASIC_AUTH_ORDER)

publicclassWebSe

curityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public UserDetailsService myUserDetailsService(){
        return new InMemoryUserDetailsManager(User.builder().username("admin").password(passwordEncoder().encode("admin")).roles("ADMIN").build());
    }
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService()).passwordEncoder(passwordEncoder());
    }
    @Bean(BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().antMatcher("/**")
                .authorizeRequests()
                .antMatchers("/","/login","/oauth/**").permitAll()
                .anyRequest().authenticated()
                .and().httpBasic().and().formLogin()
                .and().logout();
    }
}

note:首先是配置用户UserDetailsService,然后配置密码策略。主要的部分是 configure(HttpSecurity http) 方法,这里当我在formLogin()后配置了验证完成转发,即successForwardUrl(“/main”)后,sso客户端请求验证完成时,不会跳转到客户端的请求地址,而是跳转到验证成功的服务端地址 /main。

3.编写一个用户信息的controller

package com.example.oauth;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
/**
 * @author sorata
 * @date 2019-07-23 09:17
 */
@RestController
public class UserController {
    @RequestMapping("/user")
    public Principal principal(Principal principal){
        return principal;
    }
    @RequestMapping("/user2")
    public Principal principal2(Principal principal){
        return principal;
    }
}

 note: 作用就是测试和之后客户端填写的服务器用户信息的url

4.资源服务器

package com.example.oauth;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth3.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth3.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
/**
 * @author sorata
 * @date 2019-07-23 09:50
 */
@Configuration
@EnableResourceServer
public class ResourceConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().antMatcher("/user")
                .authorizeRequests().anyRequest().authenticated();
    }
}

5.完成后的效果

    spring oauth2 +springboot sso的案例分析

6. 重要的认证服务端

package com.example.oauth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth3.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth3.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth3.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth3.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth3.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth3.provider.token.TokenStore;
import org.springframework.security.oauth3.provider.token.store.InMemoryTokenStore;
/**
 * @author sorata
 * @date 2019-07-23 10:06
 */
@Configuration
@EnableAuthorizationServer
public class SsoServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired private AuthenticationManager authenticationManager;
    @Autowired private BCryptPasswordEncoder passwordEncoder;
    /**
     * 如果出现错误 在主类上去掉默认配置
     * {@link SsoServerApplication}
     */
    @Autowired private UserDetailsService detailsService;
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()")
                .passwordEncoder(passwordEncoder);
    }
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("cocos")
                .secret(passwordEncoder.encode("cocos"))
                .autoApprove(true)
                .redirectUris("http://localhost:9090/client/login")
                .scopes("all")
                .authorities("ADMIN")
                .authorizedGrantTypes("authorization_code","password","refresh_token")
                .accessTokenValiditySeconds(10000)
                .refreshTokenValiditySeconds(10000);
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(detailsService).tokenStore(tokenStore());
    }
    @Bean
    public TokenStore tokenStore(){
        return new InMemoryTokenStore();
    }
}

三、客户端

    1.客户端实现比较简单,如果想针对行的修改,自定义那么可以根据后面参考地址研读。

    2.application.properties

security.oauth3.client.authentication-scheme=form
security.oauth3.client.user-authorization-uri=http://localhost:8080/server/oauth/authorize
security.oauth3.client.access-token-uri=http://localhost:8080/server/oauth/token
security.oauth3.client.client-id=cocos
security.oauth3.client.client-secret=cocos
security.oauth3.resource.user-info-uri=http://localhost:8080/server/user
server.servlet.context-path=/client
server.port=9090

3.主类添加注解

package com.example.oauth;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth3.client.EnableOAuth3Sso;
@SpringBootApplication
@EnableOAuth3Sso
public class SsoClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(SsoClientApplication.class, args);
    }
}

  4.用户的接口

package com.example.oauth;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
/**
 * @author sorata
 * @date 2019-07-23 10:30
 */
@RestController
public class UserController {
    @RequestMapping("/user")
    public Principal principal(Principal principal){
        return principal;
    }
}

四、效果

    spring oauth2 +springboot sso的案例分析

spring oauth2 +springboot sso的案例分析

spring oauth2 +springboot sso的案例分析

spring oauth2 +springboot sso的案例分析

note: 如果想看到

spring oauth2 +springboot sso的案例分析

spring oauth2 +springboot sso的案例分析

到此,相信大家对“spring oauth2 +springboot sso的案例分析”有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

内容来源网络,如有侵权,联系删除,本文地址:https://www.230890.com/zhan/95852.html

(0)

相关推荐

  • 如何解析CSRF漏洞

    技术如何解析CSRF漏洞这篇文章给大家介绍如何解析CSRF漏洞,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。CSRF:跨站请求伪造,伪装成用户身份来执行一些非用户自愿的恶意以及非法操作CSRF和XS

    攻略 2021年12月9日
  • 哈利波特一共几部,《哈利波特》电影版共出过几部

    技术哈利波特一共几部,《哈利波特》电影版共出过几部一共七部,顺序如下:1哈利波特一共几部、哈利·波特与魔法石(Harry Potter and the Sorcerers Stone)——2001年2、哈利·波特与密室(

    生活 2021年10月19日
  • 最全分布式锁解决方案详解

    技术最全分布式锁解决方案详解 最全分布式锁解决方案详解一. 概述
    1.1 锁的概念在单进程的系统中,当存在多个线程可以同时改变某个变量(可变共享变量)时,就需要对变量或代码块做同步,使其在修改这种变量时

    礼包 2021年11月7日
  • 火柴英文,卖火柴的小女孩英文原版结局

    技术火柴英文,卖火柴的小女孩英文原版结局Once upon a time a little girl tried to make a living by selling matches in the street. Th

    生活 2021年10月26日
  • 设计模式,三)建造者模式

    技术设计模式,三)建造者模式 设计模式(三)建造者模式建造者模式建造者模式也属于创建模式,它提供了一种创建对象的最佳方式。
    定义:将一个复杂的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

    礼包 2021年11月25日
  • java如何简单快速处理 json 中的数据

    技术java如何简单快速处理 json 中的数据java如何简单快速处理 json 中的数据,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。JSONstr.j

    攻略 2021年12月2日