Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

authentication - Adding extra details to a webapi bearer token

I am trying to learn the new webapi2.1 authentication pieces.

I have got the bearer token wired up and working with my webapi. My next thing I would like to do is be able to store some additional information within the token (if possible) so when the client sends back the token I can retrieve the details without the need of them sending multiple values.

Can the token be extended to contain custom data?

Sorry if the question is a little vague but I have had a big hunt around and can't seem to find any further information

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since the token is signed with a "secret" key - only the issuer can add data to it.

You can amend something to the claim set after receiving the token in your Web API - this is called claims transformation.

I have a sample of it here: https://github.com/thinktecture/Thinktecture.IdentityModel/tree/master/samples/OWIN/AuthenticationTansformation

In essence you are writing some code that inspects the incoming token and add application specific claims to the resulting principal.

    // Transform claims to application identity
    app.UseClaimsTransformation(TransformClaims);

    private Task<ClaimsPrincipal> TransformClaims(ClaimsPrincipal incoming)
    {
        if (!incoming.Identity.IsAuthenticated)
        {
            return Task.FromResult<ClaimsPrincipal>(incoming);
        }

        // Parse incoming claims - create new principal with app claims
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Role, "foo"),
            new Claim(ClaimTypes.Role, "bar")
        };

        var nameId = incoming.FindFirst(ClaimTypes.NameIdentifier);
        if (nameId != null)
        {
            claims.Add(nameId);
        }

        var thumbprint = incoming.FindFirst(ClaimTypes.Thumbprint);
        if (thumbprint != null)
        {
            claims.Add(thumbprint);
        }

        var id = new ClaimsIdentity("Application");
        id.AddClaims(claims);

        return Task.FromResult<ClaimsPrincipal>(new ClaimsPrincipal(id));
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...