OpenId-ConnectとCookieベース認証を使用して新しいdotnetプロジェクトをセットアップしています。一部の認証サーバー(azure adなど)から受信するトークンは、RS256対称に基づいています。2つの質問があります:
1番目RS256にあるトークンにカスタム変数を追加する方法。
2番目それらをCookieで維持する方法は?
JWT.Serializersを試してみましたが、常にどこかでスタックします。
IJsonSerializer serializer = new JsonNetSerializer();
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
var algo = new JWT.Algorithms.RSAlgorithmFactory(() => new
Class1().GetByThumbprint("C11B7AF7C7910DEEB2273996BAB6033D73F6DC61"));
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algo);
これを続けるかどうかわからない。また、HS256ではhttps://jwt.io/でトークンを編集するのは簡単でした。RS256では編集できません。
Startup.Auth.cs
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(
new CookieAuthenticationOptions()
{
AuthenticationMode = AuthenticationMode.Active,
LoginPath = Microsoft.Owin.PathString.FromUriComponent("/Account/SignIn")
});
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive,
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
});
}
解決策を見つけました。
あなたはする必要はありません。OpenId接続を使用して外部サービスから受信したトークンは、基本的に認証用であり、承認用ではありません。複数の外部認証サービスを使用する場合があります。ここにカスタムクレームを追加することはお勧めできません。また、追加する必要もありません。
これは、トークンを変更する可能性がある場所です。Cookieは、外部認証サービスと同じ対称暗号ではありません。カスタムクレームを追加するために、Cookie認証方法を傍受します。
これが私がそれをした方法です:
public class CustomSecureDataFormat : ISecureDataFormat<AuthenticationTicket>
{
public string Protect(AuthenticationTicket data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
var claims = new List<Claim>();
//Custom claim
claims.Add(new Claim("HairCount", "46"));
data.Identity.AddClaims(claims);
string audienceId = AzureADConstants.GraphResourceId;
Guid guidClientId;
bool isValidAudience = Guid.TryParse(AzureADConstants.ClientId, out guidClientId);
if (!isValidAudience)
{
throw new InvalidOperationException("AuthenticationTicket.Properties does not include audience");
}
var keyByteArray = TextEncodings.Base64Url.Decode(AzureADConstants.AppKey);
var securityKey = new SymmetricSecurityKey(keyByteArray);
var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(
securityKey,
SecurityAlgorithms.HmacSha256Signature);
var issued = data.Properties.IssuedUtc;
var expires = data.Properties.ExpiresUtc;
string _issuer = AzureADConstants.Authority;
var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials);
var handler = new JwtSecurityTokenHandler();
return handler.WriteToken(token);
}
public AuthenticationTicket Unprotect(string protectedText)
{
if (string.IsNullOrWhiteSpace(protectedText))
{
throw new ArgumentNullException("protectedText");
}
var keyByteArray = TextEncodings.Base64Url.Decode(AzureADConstants.AppKey);
var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keyByteArray);
var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(
securityKey,
SecurityAlgorithms.HmacSha256Signature);
var handler = new JwtSecurityTokenHandler();
var securityToken = handler.ReadToken(protectedText);
string rawToken = ((JwtSecurityToken)securityToken).RawData;
string audienceId = AzureADConstants.GraphResourceId;
var validationParams = new TokenValidationParameters()
{
ValidateLifetime = false,
ValidAudience = audienceId,
ValidIssuer = audienceId,
ValidateIssuer = false,
ValidateAudience = false,
TokenDecryptionKey = securityKey,
IssuerSigningKey = securityKey
};
SecurityToken validatedToken;
var principal = handler.ValidateToken(rawToken, validationParams, out validatedToken);
var identity = principal.Identities;
return new AuthenticationTicket(identity.First(), new AuthenticationProperties());
}
}
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
LoginPath = Microsoft.Owin.PathString.FromUriComponent("/Account/SignIn"),
TicketDataFormat = new CustomSecureDataFormat()
});
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加