feat: support AuthnRequest in SAML (#372)

Signed-off-by: Yixiang Zhao <seriouszyx@foxmail.com>
This commit is contained in:
Yixiang Zhao 2021-12-15 21:38:00 +08:00 committed by GitHub
parent f43d01c5c2
commit 370e835499
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 66 additions and 23 deletions

View File

@ -364,11 +364,12 @@ func (c *ApiController) Login() {
func (c *ApiController) GetSamlLogin() { func (c *ApiController) GetSamlLogin() {
providerId := c.Input().Get("id") providerId := c.Input().Get("id")
authURL, err := object.GenerateSamlLoginUrl(providerId) relayState := c.Input().Get("relayState")
authURL, method, err := object.GenerateSamlLoginUrl(providerId, relayState)
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
} }
c.ResponseOk(authURL) c.ResponseOk(authURL, method)
} }
func (c *ApiController) HandleSamlLogin() { func (c *ApiController) HandleSamlLogin() {

View File

@ -48,9 +48,10 @@ type Provider struct {
Domain string `xorm:"varchar(100)" json:"domain"` Domain string `xorm:"varchar(100)" json:"domain"`
Bucket string `xorm:"varchar(100)" json:"bucket"` Bucket string `xorm:"varchar(100)" json:"bucket"`
Metadata string `xorm:"mediumtext" json:"metadata"` Metadata string `xorm:"mediumtext" json:"metadata"`
IdP string `xorm:"mediumtext" json:"idP"` IdP string `xorm:"mediumtext" json:"idP"`
IssuerUrl string `xorm:"varchar(100)" json:"issuerUrl"` IssuerUrl string `xorm:"varchar(100)" json:"issuerUrl"`
EnableSignAuthnRequest bool `json:"enableSignAuthnRequest"`
ProviderUrl string `xorm:"varchar(200)" json:"providerUrl"` ProviderUrl string `xorm:"varchar(200)" json:"providerUrl"`
} }

View File

@ -15,6 +15,7 @@
package object package object
import ( import (
"crypto/tls"
"crypto/x509" "crypto/x509"
"encoding/base64" "encoding/base64"
"fmt" "fmt"
@ -40,20 +41,32 @@ func ParseSamlResponse(samlResponse string, providerType string) (string, error)
return assertionInfo.NameID, nil return assertionInfo.NameID, nil
} }
func GenerateSamlLoginUrl(id string) (string, error) { func GenerateSamlLoginUrl(id, relayState string) (string, string, error) {
provider := GetProvider(id) provider := GetProvider(id)
if provider.Category != "SAML" { if provider.Category != "SAML" {
return "", fmt.Errorf("Provider %s's category is not SAML", provider.Name) return "", "", fmt.Errorf("Provider %s's category is not SAML", provider.Name)
} }
sp, err := buildSp(provider, "") sp, err := buildSp(provider, "")
if err != nil { if err != nil {
return "", err return "", "", err
} }
authURL, err := sp.BuildAuthURL("") auth := ""
if err != nil { method := ""
return "", err if provider.EnableSignAuthnRequest {
post, err := sp.BuildAuthBodyPost(relayState)
if err != nil {
return "", "", err
}
auth = string(post[:])
method = "POST"
} else {
auth, err = sp.BuildAuthURL(relayState)
if err != nil {
return "", "", err
}
method = "GET"
} }
return authURL, nil return auth, method, nil
} }
func buildSp(provider *Provider, samlResponse string) (*saml2.SAMLServiceProvider, error) { func buildSp(provider *Provider, samlResponse string) (*saml2.SAMLServiceProvider, error) {
@ -80,13 +93,16 @@ func buildSp(provider *Provider, samlResponse string) (*saml2.SAMLServiceProvide
ServiceProviderIssuer: fmt.Sprintf("%s/api/acs", origin), ServiceProviderIssuer: fmt.Sprintf("%s/api/acs", origin),
AssertionConsumerServiceURL: fmt.Sprintf("%s/api/acs", origin), AssertionConsumerServiceURL: fmt.Sprintf("%s/api/acs", origin),
IDPCertificateStore: &certStore, IDPCertificateStore: &certStore,
SignAuthnRequests: false,
SPKeyStore: dsig.RandomKeyStoreForTest(),
} }
if provider.Endpoint != "" { if provider.Endpoint != "" {
randomKeyStore := dsig.RandomKeyStoreForTest()
sp.IdentityProviderSSOURL = provider.Endpoint sp.IdentityProviderSSOURL = provider.Endpoint
sp.IdentityProviderIssuer = provider.IssuerUrl sp.IdentityProviderIssuer = provider.IssuerUrl
sp.SignAuthnRequests = false }
sp.SPKeyStore = randomKeyStore if provider.EnableSignAuthnRequest {
sp.SignAuthnRequests = true
sp.SPKeyStore = buildSpKeyStore()
} }
return sp, nil return sp, nil
} }
@ -99,10 +115,21 @@ func parseSamlResponse(samlResponse string, providerType string) string {
deStr := strings.Replace(string(de), "\n", "", -1) deStr := strings.Replace(string(de), "\n", "", -1)
tagMap := map[string]string{ tagMap := map[string]string{
"Aliyun IDaaS": "ds", "Aliyun IDaaS": "ds",
"Keycloak": "dsig", "Keycloak": "dsig",
} }
tag := tagMap[providerType] tag := tagMap[providerType]
expression := fmt.Sprintf("<%s:X509Certificate>([\\s\\S]*?)</%s:X509Certificate>", tag, tag) expression := fmt.Sprintf("<%s:X509Certificate>([\\s\\S]*?)</%s:X509Certificate>", tag, tag)
res := regexp.MustCompile(expression).FindStringSubmatch(deStr) res := regexp.MustCompile(expression).FindStringSubmatch(deStr)
return res[1] return res[1]
} }
func buildSpKeyStore() dsig.X509KeyStore {
keyPair, err := tls.LoadX509KeyPair("object/token_jwt_key.pem", "object/token_jwt_key.key")
if err != nil {
panic(err)
}
return &dsig.TLSCertKeyStore {
PrivateKey: keyPair.PrivateKey,
Certificate: keyPair.Certificate,
}
}

View File

@ -13,7 +13,7 @@
// limitations under the License. // limitations under the License.
import React from "react"; import React from "react";
import {Button, Card, Col, Input, InputNumber, Row, Select} from 'antd'; import {Button, Card, Col, Input, InputNumber, Row, Select, Switch} from 'antd';
import {LinkOutlined} from "@ant-design/icons"; import {LinkOutlined} from "@ant-design/icons";
import * as ProviderBackend from "./backend/ProviderBackend"; import * as ProviderBackend from "./backend/ProviderBackend";
import * as Setting from "./Setting"; import * as Setting from "./Setting";
@ -418,6 +418,16 @@ class ProviderEditPage extends React.Component {
</React.Fragment> </React.Fragment>
) : this.state.provider.category === "SAML" ? ( ) : this.state.provider.category === "SAML" ? (
<React.Fragment> <React.Fragment>
<Row style={{marginTop: '20px'}} >
<Col style={{marginTop: '5px'}} span={(Setting.isMobile()) ? 22 : 2}>
{Setting.getLabel(i18next.t("provider:Sign request"), i18next.t("provider:Sign request - Tooltip"))} :
</Col>
<Col span={22} >
<Switch checked={this.state.provider.enableSignAuthnRequest} onChange={checked => {
this.updateProviderField('enableSignAuthnRequest', checked);
}} />
</Col>
</Row>
<Row style={{marginTop: '20px'}} > <Row style={{marginTop: '20px'}} >
<Col style={{marginTop: '5px'}} span={(Setting.isMobile()) ? 22 : 2}> <Col style={{marginTop: '5px'}} span={(Setting.isMobile()) ? 22 : 2}>
{Setting.getLabel(i18next.t("provider:Metadata"), i18next.t("provider:Metadata - Tooltip"))} : {Setting.getLabel(i18next.t("provider:Metadata"), i18next.t("provider:Metadata - Tooltip"))} :

View File

@ -77,8 +77,8 @@ export function unlink(values) {
}).then(res => res.json()); }).then(res => res.json());
} }
export function getSamlLogin(providerId) { export function getSamlLogin(providerId, relayState) {
return fetch(`${authConfig.serverUrl}/api/get-saml-login?id=${providerId}`, { return fetch(`${authConfig.serverUrl}/api/get-saml-login?id=${providerId}&relayState=${relayState}`, {
method: 'GET', method: 'GET',
credentials: 'include', credentials: 'include',
}).then(res => res.json()); }).then(res => res.json());

View File

@ -201,9 +201,13 @@ class LoginPage extends React.Component {
let realRedirectUri = params.get("redirect_uri"); let realRedirectUri = params.get("redirect_uri");
let redirectUri = `${window.location.origin}/callback/saml`; let redirectUri = `${window.location.origin}/callback/saml`;
let providerName = provider.name; let providerName = provider.name;
AuthBackend.getSamlLogin(`${provider.owner}/${providerName}`).then((res) => { let relayState = `${clientId}&${application}&${providerName}&${realRedirectUri}&${redirectUri}`;
const replyState = `${clientId}&${application}&${providerName}&${realRedirectUri}&${redirectUri}`; AuthBackend.getSamlLogin(`${provider.owner}/${providerName}`, btoa(relayState)).then((res) => {
window.location.href = `${res.data}&RelayState=${btoa(replyState)}`; if (res.data2 === "POST") {
document.write(res.data)
} else {
window.location.href = res.data
}
}); });
} }