oauth2.0實現sso單點登入的方式和相關程式碼

weixin_33912246發表於2018-07-27

oauth2.0實現sso單點登入的方式和相關程式碼

SSO介紹

什麼是SSO

百科:SSO英文全稱Single Sign On,單點登入。SSO是在多個應用系統中,使用者只需要登入一次就可以訪問所有相互信任的應用系統。它包括可以將這次主要的登入對映到其他應用中用於同一個使用者的登入的機制。它是目前比較流行的企業業務整合的解決方案之一。

簡單來說,SSO出現的目的在於解決同一產品體系中,多應用共享使用者session的需求。SSO通過將使用者登入資訊對映到瀏覽器cookie中,解決其它應用免登獲取使用者session的問題。

為什麼需要SSO

開放平臺業務本身不需要SSO,但是如果平臺的普通使用者也可以在申請後成為一個應用開發者,那麼就需要將平臺加入到公司的整體賬號體系中去,另外,對於企業級場景來說,一般都會有SSO系統,充當統一的賬號校驗入口。

CAS協議中概念介紹

SSO單點登入只是一個方案,而目前市面上最流行的單端登入系統是由耶魯大學開發的CAS系統,而由其實現的CAS協議,也成為目前SSO協議中的既定協議,下文中的單點登入協議及結構,均為CAS中的體現結構
CAS協議中有以下幾個概念:
1.CAS Client:需要整合單點登入的應用,稱為單點登入客戶端
2.CAS Server:單點登入伺服器,使用者登入鑑權、憑證下發及校驗等操作
3.TGT:ticker granting ticket,使用者憑證票據,用以標記使用者憑證,使用者在單點登入系統中登入一次後,再其有效期內,TGT即代表使用者憑證,使用者在其它client中無需再進行二次登入操作,即可共享單點登入系統中的已登入使用者資訊
4.ST:service ticket,服務票據,服務可以理解為客戶端應用的一個業務模組,體現為客戶端回撥url,CAS用以進行服務許可權校驗,即CAS可以對接入的客戶端進行管控
5.TGC:ticket granting cookie,儲存使用者票據的cookie,即使用者登入憑證最終對映的cookies

CAS核心協議介紹

12057079-389a252eda961807.png
image.png

1.使用者在瀏覽器中訪問應用 2.應用發現需要索要使用者資訊,跳轉至SSO伺服器 3.SSO伺服器向使用者展示登入介面,使用者進行登入操作,SSO伺服器進行使用者校驗後,對映出TGC 4.SSO伺服器向回撥應用服務url,返回ST 5.應用去SSO伺服器校驗ST許可權及合法性 6.SSO伺服器校驗成功後,返回使用者資訊

CAS基本流程介紹

以下為基本的CAS協議流程,圖一為初次登入時的流程,圖二為已進行過一次登入後的流程

12057079-512283b3cd687c9d.png
image.png
12057079-d08a7c14a0926cc0.png
image.png

以上是oauth的單點登入的流程,下面我們來看下應該如何配置單點登入:

繼承了WebSecurityConfigurerAdapter的類上加@EnableOAuth2Sso註解來表示支援單點登入:

@Configuration
@EnableOAuth2Sso
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {}

另外還需要在應用中新增如下的兩個類:

SsoApprovalEndpoint:

package urity.demo.sso;

import org.apache.catalina.util.ParameterMap;
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 javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@SessionAttributes("authorizationRequest")
public class SsoApprovalEndpoint {

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

    protected String createTemplate(Map<String, Object> model, HttpServletRequest request) {
        //解決從登入跳轉到授權 和 應用之間跳轉授權 form表單內action值相同 導致無法完成授權的問題
        if((request.getParameterMap()) instanceof ParameterMap){
            this.DENIAL="<form id='denialForm' name='denialForm' action='${path}/oauth/authorize' method='post' style='display: inline-block;margin-left: 15px; ' ><input name='user_oauth_approval' value='false' type='hidden'/>%csrf%<label><input class='sub' name='deny' value='取消' type='submit' /></label></form>";
            this.TEMPLATE="<html><head><style type='text/css'>.sub{width: 100px;background: grey;color: #fff;transition: all 1s;}.sub:hover{background-color: #FFF;color: black;transition: all 1s;transition: all 1s;}"
                    +"</style></head><body style='background-color: #eee;'><div style='text-align: center; margin-top: 35px;'><h1>認證授權</h1>"
                    + "<p>你確定授權應用 '【${authorizationRequest.clientId}】' 登入並訪問你的資訊?</p>"
                    + "<form id='confirmationForm' name='confirmationForm' action='${path}/oauth/authorize' method='post' style='display: inline-block;margin-right: 15px;  ' ><input name='user_oauth_approval' value='true' type='hidden'/>%csrf%%scopes%<label><input class='sub' name='authorize' value='確定' type='submit' /></label></form>"
                    + "%denial%</div></body></html>";
        }else{
            this.DENIAL="<form id='denialForm' name='denialForm' action='/oauth/authorize' method='post' style='display: inline-block;margin-left: 15px; ' ><input name='user_oauth_approval' value='false' type='hidden'/>%csrf%<label><input class='sub' name='deny' value='取消' type='submit' /></label></form>";
            this.TEMPLATE="<html><head><style type='text/css'>.sub{width: 100px;background: grey;color: #fff;transition: all 1s;}.sub:hover{background-color: #FFF;color: black;transition: all 1s;}"
                    +"</style></head><body style='background-color: #eee;'><div style='text-align: center; margin-top: 35px;'><h1>認證授權</h1>"
                    + "<p>你確定授權應用 '【${authorizationRequest.clientId}】' 登入並訪問你的資訊?</p>"
                    + "<form id='confirmationForm' name='confirmationForm' action='/oauth/authorize' method='post' style='display: inline-block;margin-right: 15px;  ' ><input name='user_oauth_approval' value='true' type='hidden'/>%csrf%%scopes%<label><input class='sub' name='authorize' value='確定' type='submit' /></label></form>"
                    + "%denial%</div></body></html>";
        }

        String template = TEMPLATE;
        if (model.containsKey("scopes") || request.getAttribute("scopes") != null) {
            template = template.replace("%scopes%", createScopes(model, request)).replace("%denial%", "");
        }
        else {
            template = template.replace("%scopes%", "").replace("%denial%", DENIAL);
        }
        if (model.containsKey("_csrf") || request.getAttribute("_csrf") != null) {
            template = template.replace("%csrf%", CSRF);
        }
        else {
            template = template.replace("%csrf%", "");
        }
        return template;
    }

    private CharSequence createScopes(Map<String, Object> model, HttpServletRequest request) {
        StringBuilder builder = new StringBuilder("<ul>");
        @SuppressWarnings("unchecked")
        Map<String, String> scopes = (Map<String, String>) (model.containsKey("scopes") ? model.get("scopes") : request
                .getAttribute("scopes"));
        for (String scope : scopes.keySet()) {
            String approved = "true".equals(scopes.get(scope)) ? " checked" : "";
            String denied = !"true".equals(scopes.get(scope)) ? " checked" : "";
            String value = SCOPE.replace("%scope%", scope).replace("%key%", scope).replace("%approved%", approved)
                    .replace("%denied%", denied);
            builder.append(value);
        }
        builder.append("</ul>");
        return builder.toString();
    }

    private static String CSRF = "<input type='hidden' name='${_csrf.parameterName}' value='${_csrf.token}' />";

    private  String DENIAL = "<form id='denialForm' name='denialForm' action='/oauth/authorize' method='post' style='display: inline-block;margin-left: 15px; ' ><input name='user_oauth_approval' value='false' type='hidden'/>%csrf%<label><input class='sub' name='deny' value='取消' type='submit' /></label></form>";

    //    private static String TEMPLATE = "<html><body><div style='display:none;'><h1>OAuth Approval</h1>"
//            + "<p>Do you authorize '${authorizationRequest.clientId}' to access your protected resources?</p>"
//            + "<form id='confirmationForm' name='confirmationForm' action='${path}/oauth/authorize' method='post'><input name='user_oauth_approval' value='true' type='hidden'/>%csrf%%scopes%<label><input name='authorize' value='Authorize' type='submit'/></label></form>"
//            + "%denial%</div><script>document.getElementById('confirmationForm').submit()</script></body></html>";
    private  String TEMPLATE = "<html><head><style type='text/css'>.sub{width: 100px;background: grey;color: #fff;}.sub:hover{background-color: #FFF;color: black;}"
            +"</style></head><body style='background-color: #eee;'><div style='text-align: center; margin-top: 35px;'><h1>認證授權</h1>"
            + "<p>你確定授權應用 '【${authorizationRequest.clientId}】' 登入並訪問你的資訊?</p>"
            + "<form id='confirmationForm' name='confirmationForm' action='/oauth/authorize' method='post' style='display: inline-block;margin-right: 15px;  ' ><input name='user_oauth_approval' value='true' type='hidden'/>%csrf%%scopes%<label><input class='sub' name='authorize' value='確定' type='submit' /></label></form>"
            + "%denial%</div></body></html>";


    private static String SCOPE = "<li><div class='form-group'>%scope%: <input type='radio' name='%key%'"
            + " value='true'%approved%>Approve</input> <input type='radio' name='%key%' value='false'%denied%>Deny</input></div></li>";



}

SsoSpelView:

package urity.demo.sso;

import org.springframework.context.expression.MapAccessor;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.security.oauth2.common.util.RandomValueStringGenerator;
import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

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

public class SsoSpelView implements View {
    private final String template;
    private final String prefix;
    private final SpelExpressionParser parser = new SpelExpressionParser();
    private final StandardEvaluationContext context = new StandardEvaluationContext();
    private PropertyPlaceholderHelper.PlaceholderResolver resolver;

    public SsoSpelView(String template) {
        this.template = template;
        this.prefix = new RandomValueStringGenerator().generate() + "{";
        this.context.addPropertyAccessor(new MapAccessor());
        this.resolver = new PropertyPlaceholderHelper.PlaceholderResolver() {
            public String resolvePlaceholder(String name) {
                Expression expression = parser.parseExpression(name);
                Object value = expression.getValue(context);
                return value == null ? null : value.toString();
            }
        };
    }

    public String getContentType() {
        return "text/html";
    }

    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Map<String, Object> map = new HashMap<String, Object>(model);
        String path = ServletUriComponentsBuilder.fromContextPath(request).build()
                .getPath();
        map.put("path", (Object) path==null ? "" : path);
        context.setRootObject(map);
        String maskedTemplate = template.replace("${", prefix);
        PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper(prefix, "}");
        String result = helper.replacePlaceholders(maskedTemplate, resolver);
        result = result.replace(prefix, "${");
        response.setContentType(getContentType());
        response.getWriter().append(result);
    }

}

分析:SsoApprovalEndpoint這個類的來源於WhitelabelApprovalEndpoint這個類,主要用於單點登入是否授權進入用的,預設會有有個白色的授權頁面出現讓客戶選擇是否授權登入,看下原始碼:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.security.oauth2.provider.endpoint;

import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

@FrameworkEndpoint
@SessionAttributes({"authorizationRequest"})
public class WhitelabelApprovalEndpoint {
    private static String CSRF = "<input type='hidden' name='${_csrf.parameterName}' value='${_csrf.token}' />";
    private static String DENIAL = "<form id='denialForm' name='denialForm' action='${path}/oauth/authorize' method='post'><input name='user_oauth_approval' value='false' type='hidden'/>%csrf%<label><input name='deny' value='Deny' type='submit'/></label></form>";
    private static String TEMPLATE = "<html><body><h1>OAuth Approval</h1><p>Do you authorize '${authorizationRequest.clientId}' to access your protected resources?</p><form id='confirmationForm' name='confirmationForm' action='${path}/oauth/authorize' method='post'><input name='user_oauth_approval' value='true' type='hidden'/>%csrf%%scopes%<label><input name='authorize' value='Authorize' type='submit'/></label></form>%denial%</body></html>";
    private static String SCOPE = "<li><div class='form-group'>%scope%: <input type='radio' name='%key%' value='true'%approved%>Approve</input> <input type='radio' name='%key%' value='false'%denied%>Deny</input></div></li>";

    public WhitelabelApprovalEndpoint() {
    }

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

        return new ModelAndView(new SpelView(template), model);
    }

    protected String createTemplate(Map<String, Object> model, HttpServletRequest request) {
        String template = TEMPLATE;
        if (!model.containsKey("scopes") && request.getAttribute("scopes") == null) {
            template = template.replace("%scopes%", "").replace("%denial%", DENIAL);
        } else {
            template = template.replace("%scopes%", this.createScopes(model, request)).replace("%denial%", "");
        }

        if (!model.containsKey("_csrf") && request.getAttribute("_csrf") == null) {
            template = template.replace("%csrf%", "");
        } else {
            template = template.replace("%csrf%", CSRF);
        }

        return template;
    }

    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" : "";
            String value = SCOPE.replace("%scope%", scope).replace("%key%", scope).replace("%approved%", approved).replace("%denied%", denied);
            builder.append(value);
        }

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

TEMPLATE這裡面的網頁程式碼字串就是相關的授權頁面,顯示是否授權或者拒絕授權的頁面,當我們選擇授權後我們會跳轉到另一個伺服器的頁面.

如果我們不想讓它顯示出來授權頁面(因為這樣會影響使用者體驗),我們可以在原始的文件中寫<scripts>程式碼讓它自動提交,如下所示:

  private static String TEMPLATE = "<html><body><div style='display:none;'><h1>OAuth Approval</h1>"
            + "<p>Do you authorize '${authorizationRequest.clientId}' to access your protected resources?</p>"
           + "<form id='confirmationForm' name='confirmationForm' action='${path}/oauth/authorize' method='post'><input name='user_oauth_approval' value='true' type='hidden'/>%csrf%%scopes%<label><input name='authorize' value='Authorize' type='submit'/></label></form>"
           + "%denial%</div>
           <script>document.getElementById('confirmationForm').submit()</script></body></html>";
   

我們用<div style='display:none;'>來表示這個頁面是空白的,然後我們加上<script>的編寫來自動提交,形成一個空白頁面一閃而過的效果(不需要再手動點選授權)

遇到的坑總結:

時常配置好後報出如下錯誤:

***************************
APPLICATION FAILED TO START
***************************

Description:

Method springSecurityFilterChain in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration required a single bean, but 4 were found:
    - remoteTokenServices: defined by method 'remoteTokenServices' in class path resource [org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfiguration$RemoteTokenServicesConfiguration$TokenInfoServicesConfiguration.class]
    - consumerTokenServices: defined by method 'consumerTokenServices' in class path resource [org/springframework/security/oauth2/config/annotation/web/configuration/AuthorizationServerEndpointsConfiguration.class]
    - defaultAuthorizationServerTokenServices: defined by method 'defaultAuthorizationServerTokenServices' in class path resource [org/springframework/security/oauth2/config/annotation/web/configuration/AuthorizationServerEndpointsConfiguration.class]
    - defaultTokenServices: defined by method 'defaultTokenServices' in class path resource [urity/demo/oauth2/AuthorizationServerConfiguration.class]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed


這個是security找不到使用哪個類報錯的問題,這裡是資源類不明,所以我們在資源的相關配置上加上@Primary註解來解決:

/**
     * 建立一個預設的資源服務token
     *
     * @return
     */
    @Bean
    @Primary
    public ResourceServerTokenServices defaultTokenServices() {
        final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenEnhancer(accessTokenConverter());
        defaultTokenServices.setTokenStore(jwtStore());
        return defaultTokenServices;
    }

相關文章