c# - Web API 和 Angular 5 token 身份验证 - 登录后获取用户信息

标签 c# angular authentication asp.net-web-api token

当我访问我的 Angular 应用程序时,我得到了这个:

access_token:"******************"
expires_in:59
refresh_token:"******************"
token_type:"bearer"

但现在我想使用登录用户的信息。我的问题是我不能,因为我没有 token 信息之间的用户 ID。

这是我从 API 登录的 C#:

//Varifying user credentials
    public bool Login(string userName, string password)
    {
        try
        {
            ServiceContext db = new ServiceContext();
            var userInfo = db.Users.Where(x => x.Username == userName).FirstOrDefault();
            if (userInfo != null)
            {
                string stringPwd = Encoding.ASCII.GetString(userInfo.Password);
                return stringPwd == password;
            }
            else
            {
                return false;
            }
        }
        catch (Exception ex)
        {
            return false;
        }
    }

这是我在 Angular 应用程序中的身份验证服务:

@Injectable()
export class AuthenticationService {
constructor(private http: HttpClient) { }

login(username: string, password: string) {

    var data = "grant_type=password" + "&username=" + username + "&password=" + password;
    var reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-urlencoded','No-Auth':'True' });
    return this.http.post<any>(`${environment.apiUrl}/token`, data, { headers: reqHeader })
        .pipe(map(user => {
            // login successful if there's a jwt token in the response
            if (user && user.access_token) {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify(user));
            }
            return user;
        }));
}

这是我的 GrantResourceOwnerCredentials:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        Accounts acc = new Accounts();

        //Authenticate the user credentials
        if (acc.Login(context.UserName, context.Password))
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, acc.GetUserRole(context.UserName)));
            identity.AddClaim(new Claim("username", context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            context.Validated(identity);
        }
        else
        {
            context.SetError("invalid_grant", "Provided username and password is incorrect");
            return;
        }
    }

我想显示用于登录的用户名。有人可以帮助我并给我一些建议吗?

提前致谢

最佳答案

修改您的 GrantResourceOwnerCredentials 方法,如下所示

您需要使用 AuthenticationProperties,您可以使用 token 数据添加更多参数。

AuthenticationTicket 会将您添加的参数绑定(bind)到您的 token 数据,您将在您的 Angular 应用程序中访问这些数据。

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{

    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    Accounts acc = new Accounts();

    //Authenticate the user credentials
    if (acc.Login(context.UserName, context.Password))
    {   
        //If you want to display user's firstname, lastname, or picture then
        //The below method is for getting user from database by its username
        var user = acc.GetUserByUsername(context.UserName);
        string firstName = user.FirstName;
        string lastName = user.LastName;

        identity.AddClaim(new Claim(ClaimTypes.Role, acc.GetUserRole(context.UserName)));
        identity.AddClaim(new Claim("username", context.UserName));
        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

        var props = new AuthenticationProperties(new Dictionary<string, string>
                    {                             
                         {
                             "userName", context.UserName
                         },
                         {
                             "firstName", firstName
                         },
                         {
                             "lastName", lastName
                         }
                    });

        var ticket = new AuthenticationTicket(identity, props);
        context.Validated(ticket);
    }
    else
    {
        context.SetError("invalid_grant", "Provided username and password is incorrect");
        return;
    }
}

并将此方法添加到 GrantResourceOwnerCredentials 的下方

public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
    foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
    {
        context.AdditionalResponseParameters.Add(property.Key, property.Value);
    }

    return Task.FromResult<object>(null);
}

输出:

access_token:"******************"
expires_in:59
refresh_token:"******************"
token_type:"bearer",
firstName: "Abc",
lastName: "Pqr",
userName: "Xyz"

关于c# - Web API 和 Angular 5 token 身份验证 - 登录后获取用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52361623/

相关文章:

html - mat-table 不会被来自restservice 的数据填充

wcf - 如何为需要客户端身份验证证书的 Web 服务添加对 WCF 客户端的服务引用

c# - 开放认证 - 供应商

c# - 将数组从 C# COM 库返回到 VBA

java - Android 创建日历事件总是作为生日

javascript - 查找数组中现有的对象

asp.net - 在 ASP.NET 5 中跨子域共享身份验证 Cookie

c# - iOS和C#之间的AES加密

c# - 在 IIS 下的 ASP.net 网站中使用 C# 从 Windows 通用凭据存储中检索凭据

angular - ASP.NET Core 发布排除文件夹(或 .json 文件)