Angularアプリにアクセスすると、次のようになります。
access_token:"******************"
expires_in:59
refresh_token:"******************"
token_type:"bearer"
でも今はログインしたユーザーの情報を使いたいのですが、トークン情報の間にユーザー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
トークンデータでさらにパラメータを追加できることを使用する必要があります。
そしてAuthenticationTicket
、追加したパラメーターをトークンデータにバインドし、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"
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加