【Spring Security开发安全的REST服务】- 6.10 基于JWT实现SSO单点登录1和2

本次学习demo是基于Springboot 2.1.5版本,于教学视频中的在代码上多出会存在差异

理论介绍

在这里插入图片描述

6.10.1、创建新的项目包

在选中moss-security右键new Module;选择Maven直接点击next
在这里插入图片描述
在ArtifactId中填写项目名称后点击next;
在这里插入图片描述
修改下名称后点击Finish;
在这里插入图片描述
按照上述步骤,依次创建demo,server,client1,client2工程目录如下
在这里插入图片描述

6.10.2、实现认证服务器

在pom中添加项目依赖

<dependencies>
    <!--SpringBoot基础jar包-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
        <version>2.1.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-jwt</artifactId>
        <version>1.0.9.RELEASE</version>
    </dependency>
</dependencies>
6.10.2.1 编写SpringBoot项目启动类

在项目根路径下创建该类

package com.moss;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * server项目启动类
 *
 * @author lwj
 */
@SpringBootApplication
public class SsoServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(SsoServerApplication.class, args);
    }
}

6.10.2.2 认证服务器类

在项目目录下,创建com.moss.sso.server包,在server包中创建该类

package com.moss.sso.server;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * 认证服务器
 *
 * @author lwj
 */
@Configuration
@EnableAuthorizationServer
public class SsoAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client1")
                .secret("clientSecret1")
                .authorizedGrantTypes("authorization_code", "refresh_token")
                .scopes("all")
                .and()
                .withClient("client2")
                .secret("clientSecret2")
                .authorizedGrantTypes("authorization_code", "refresh_token")
                .scopes("all");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(JwtTokenStore())
                .accessTokenConverter(jwtAccessTokenConverter());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //  让其他应用可以通过认证的方式来访问
        security.tokenKeyAccess("isAuthenticated()");
    }

    @Bean
    public TokenStore JwtTokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
        //  设置密签
        accessTokenConverter.setSigningKey("moss");
        return accessTokenConverter;
    }
}

6.10.2.3 认证服务器application.yml配置类编写
server:
  port: 9999
  servlet:
    context-path: /server
spring:
  security:
    user:
      name: admin
      password: 123456

6.10.3 实现Client1

此处要注意,在下面的项目启动类中添加的@EnableOAuth2Sso注解,需要用到下面的spring-security-oauth2-autoconfigure中的;否则会报错。

<dependencies>
    <!--SpringBoot基础jar包-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
        <version>2.1.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        <version>2.1.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-jwt</artifactId>
        <version>1.0.9.RELEASE</version>
    </dependency>
</dependencies>
6.10.3.1 Client1项目启动类

在sso-client1项目的根目录下创建项目启动类,并将启动类注解为RestController,添加/user测试获取用户资源;
该处要注意的是

package com.moss;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * client1启动类
 *
 * @author lwj
 */
@SpringBootApplication
@RestController
@EnableOAuth2Sso
public class SsoClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(SsoClientApplication.class, args);
    }

    @GetMapping("/user")
    public Authentication user(Authentication user) {
        return user;
    }

}

6.10.3.2 Client1项目application.yml配置类编写
server:
  port: 8080
  servlet:
    context-path: /client1


security:
  oauth2:
    client:
      client-id: client1
      client-secret: clientSecret1
      user-authorization-uri: http://127.0.0.1:9999/server/oauth/authorize
      access-token-uri: http://127.0.0.1:9999/server/oauth/token
      token-info-uri: http://127.0.0.1:9999/server/oauth/check_token
    resource:
      jwt:
        key-uri: http://127.0.0.1:9999/server/oauth/token_key
6.10.3.3 添加index.html页面测试跳转

在resources下创建static文件夹,在文件夹中创建index.html,具体代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Client1</title>
</head>
<body>
    <h1>SSO Demo Client1</h1>
    <a href="http://127.0.0.1:8060/client2/index.html">访问Client2</a>
</body>
</html>
6.10.3.4 Client1项目工程全目录

Client1项目工程全目录

6.10.4 实现Client2

Client2与CLInet1基本类似,不同的地方在下面两个代码处

6.10.4.1 application.yml配置文件
server:
  port: 8060
  servlet:
    context-path: /client2


security:
  oauth2:
    client:
      client-id: client2
      client-secret: clientSecret2
      user-authorization-uri: http://127.0.0.1:9999/server/oauth/authorize
      access-token-uri: http://127.0.0.1:9999/server/oauth/token
      token-info-uri: http://127.0.0.1:9999/server/oauth/check_token
    resource:
      jwt:
        key-uri: http://127.0.0.1:9999/server/oauth/token_key
6.10.4.2 index.html测试页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Client2</title>
</head>
<body>
    <h1>SSO Demo Client2</h1>
    <a href="http://127.0.0.1:8080/client1/index.html">访问Client2</a>
</body>
</html>
6.10.4.3 Client2项目工程全目录

Client2项目工程全目录

6.10.5 测试与调整

至此,我们跟着视频码好了代码,接着我们就去测试,依次启动server,client1,client2;
在启动client1的时候,我们发现后台报错了,client1中的报错,大致如下
在这里插入图片描述
但是我们在server的控制台中也发现了报错
在这里插入图片描述大致应该是client1在启动的时候,通过配置的clientId和clientsecret去认证服务器调用的时候发现clientsecret没有密码加密器

简单说就是下面的这个配置中红色框的secret我们写的是明文,并没有使用加密器去做加密,但是security5默认是需要我们去指定加密器的
在这里插入图片描述
如下图,我们可以指定一个官方认为最牛逼的加密器

在这里插入图片描述
重启应用测试,这次我们发现应用可以起起来了;
在浏览器中输入http://localhost:8080/client1
但是并没有像视频中的直接跳出Basic登录框而是又一个错误页面
在这里插入图片描述
从上面的错误中,我们可以看到,用户需要认证。我们需要在com.moss.sso.server中去配置一个配置类

========================================================================================================
备注Question:但是这个地方为什么配置下这个配置类就能够解决上面的这个问题不是很理解???

2020年1月8日追加:
这里其实是因为在写了下面的这个MyWebSecurityConfigurerAdapter类,而这个类继承了WebSecurityConfigurerAdapter这个类。这个类中为我们做了默认的security相关的设置。
在这里插入图片描述

package com.moss.sso.server;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Security配置类
 *
 * @author lwj
 */
@Configuration
public class MyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {


}

至此,我们再次重启项目
在浏览器中使用该网址http://localhost:8080/client1;
在这里插入图片描述
页面成功跳出登录界面,和视频中的跳出baisc认证的方式不一样;如果我们需要使用basic认证的话,我们可以在上述的MyWebSecurityConfigurerAdapter 类中添加如下方法,则登录方式会变成弹出框的样式;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .httpBasic()
//                .formLogin()  // 更改为form表单登录
                .and()
                // 所有的请求都必须授权后才能访问
                .authorizeRequests()
                .anyRequest()
                .authenticated();
        ;
    }

我们先用账号和密码登陆但是我们发现有报了一个重定向错误,如下
在这里插入图片描述
查看了网址栏中的这个redirect_uri=http://localhost:8080/client1/login;这个和我在server中配置的回调url是不同的,那边写的是127.0.0.1;也就是说,我在一开始进行测试的时候,需要使用到和我在server中配置的前缀相同的名称;
在浏览器中重新使用http://127.0.0.1:8080/client1来访问;
在这里插入图片描述
页面展示正确,点击Authorize;

在这里插入图片描述
点击“访问Client2”
在这里插入图片描述点击Authorize
在这里插入图片描述
之后可以自在;两个浏览器之间相互切换;

6.10.6 修改登录校验

将原来在server项目的application.yml中配置的用户名密码登陆的方式,修改为可以配置连接数据库的方式

6.10.6.1 添加SsoUserDetailServiceImpl类
package com.moss.sso.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 登录方法
 *
 * @author lwj
 */
@Component
public class SsoUserDetailServiceImpl implements UserDetailsService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String password = passwordEncoder.encode("123456");
        logger.info("用户名 {},数据库密码{}", username, password);
        User admin = new User(username,
//                              "{noop}123456",
                password,
                true, true, true, true,
                AuthorityUtils.commaSeparatedStringToAuthorityList(""));
        return admin;
    }
}

6.10.6.2 在MyWebSecurityConfigurerAdapter类中添加配置
package com.moss.sso.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Security配置类
 *
 * @author lwj
 */
@Configuration
public class MyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Qualifier("ssoUserDetailServiceImpl")
    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("123456").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .httpBasic()
//                .formLogin()  // 更改为form表单登录
                .and()
                // 所有的请求都必须授权后才能访问
                .authorizeRequests()
                .anyRequest()
                .authenticated();
        ;
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

}

重启项目后,我们就需要通过自己的登陆校验方式来登陆校验了。

6.10.7 去掉登陆授权过程

**分析:**从之前的登陆流程上看,授权的过程就是中间多了一个表单,然后点击授权,也就是只要在找到授权表单的地方,把这个页面的表单设为不可见,并且在表单展示出来的时候就把表单提交掉就可以了。

在项目中添加SsoWhitelabelApprovalEndpoint类

package com.moss.sso.server;

import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.Map;

/**
 * 自定义的授权页面
 *
 * @author lwj
 */
@RestController
@SessionAttributes({"authorizationRequest"})
public class SsoWhitelabelApprovalEndpoint {

    public SsoWhitelabelApprovalEndpoint() {
    }

    @RequestMapping({"/oauth/confirm_access"})
    public ModelAndView getAccessConfirmation(Map<String, Object> model, HttpServletRequest request) throws Exception {
        final String approvalContent = this.createTemplate(model, request);
        if (request.getAttribute("_csrf") != null) {
            model.put("_csrf", request.getAttribute("_csrf"));
        }

        View approvalView = new View() {
            @Override
            public String getContentType() {
                return "text/html";
            }

            @Override
            public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
                response.setContentType(this.getContentType());
                response.getWriter().append(approvalContent);
            }
        };
        return new ModelAndView(approvalView, model);
    }

    protected String createTemplate(Map<String, Object> model, HttpServletRequest request) {
        AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");
        String clientId = authorizationRequest.getClientId();
        StringBuilder builder = new StringBuilder();
        // style='display:none;'设置body不显示
        builder.append("<html><body style='display:none;'><h1>OAuth Approval</h1>");
        builder.append("<p>Do you authorize \"").append(HtmlUtils.htmlEscape(clientId));
        builder.append("\" to access your protected resources?</p>");
        builder.append("<form id=\"confirmationForm\" name=\"confirmationForm\" action=\"");
        String requestPath = ServletUriComponentsBuilder.fromContextPath(request).build().getPath();
        if (requestPath == null) {
            requestPath = "";
        }

        builder.append(requestPath).append("/oauth/authorize\" method=\"post\">");
        builder.append("<input name=\"user_oauth_approval\" value=\"true\" type=\"hidden\"/>");
        String csrfTemplate = null;
        CsrfToken csrfToken = (CsrfToken) ((CsrfToken) (model.containsKey("_csrf") ? model.get("_csrf") : request.getAttribute("_csrf")));
        if (csrfToken != null) {
            csrfTemplate = "<input type=\"hidden\" name=\"" + HtmlUtils.htmlEscape(csrfToken.getParameterName()) + "\" value=\"" + HtmlUtils.htmlEscape(csrfToken.getToken()) + "\" />";
        }

        if (csrfTemplate != null) {
            builder.append(csrfTemplate);
        }

        String authorizeInputTemplate = "<label><input name=\"authorize\" value=\"Authorize\" type=\"submit\"/></label></form>";
        if (!model.containsKey("scopes") && request.getAttribute("scopes") == null) {
            builder.append(authorizeInputTemplate);
            builder.append("<form id=\"denialForm\" name=\"denialForm\" action=\"");
            builder.append(requestPath).append("/oauth/authorize\" method=\"post\">");
            builder.append("<input name=\"user_oauth_approval\" value=\"false\" type=\"hidden\"/>");
            if (csrfTemplate != null) {
                builder.append(csrfTemplate);
            }

            builder.append("<label><input name=\"deny\" value=\"Deny\" type=\"submit\"/></label></form>");
        } else {
            builder.append(this.createScopes(model, request));
            builder.append(authorizeInputTemplate);
        }
        //  添加提交表单的事件
        builder.append("<script>document.getElementById('confirmationForm').submit()</script>");
        builder.append("</body></html>");
        return builder.toString();
    }

    private CharSequence createScopes(Map<String, Object> model, HttpServletRequest request) {
        StringBuilder builder = new StringBuilder("<ul>");
        Map<String, String> scopes = (Map) ((Map) (model.containsKey("scopes") ? model.get("scopes") : request.getAttribute("scopes")));
        Iterator var5 = scopes.keySet().iterator();

        while (var5.hasNext()) {
            String scope = (String) var5.next();
            String approved = "true".equals(scopes.get(scope)) ? " checked" : "";
            String denied = !"true".equals(scopes.get(scope)) ? " checked" : "";
            scope = HtmlUtils.htmlEscape(scope);
            builder.append("<li><div class=\"form-group\">");
            builder.append(scope).append(": <input type=\"radio\" name=\"");
            builder.append(scope).append("\" value=\"true\"").append(approved).append(">Approve</input> ");
            builder.append("<input type=\"radio\" name=\"").append(scope).append("\" value=\"false\"");
            builder.append(denied).append(">Deny</input></div></li>");
        }

        builder.append("</ul>");
        return builder.toString();
    }
}

这里和视频教程中的老版本的有一些差异,差异点在代码中需要用到的一个approvalView在老的版本中是没有继承的,需要去再添加一个view类,但是在新版本中这个方法只要添加@Overwrite注解即可。
需要修改的两个地方在上面代码注释的地方。
重启项目我们发现在点击登录之后就不会出现需要手动授权的界面了。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值