public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
bool isvalidUser = AuthenticateUser(context.UserName, context.Password);// validate my user&password
if (!isvalidUser)
{
context.Rejected();
return;
}
// create identity
var id = new ClaimsIdentity(context.Options.AuthenticationType);
id.AddClaim(new Claim("sub", context.UserName));
id.AddClaim(new Claim("role", "user"));
// create metadata to pass on to refresh token provider
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{ "as:client_id", context.ClientId }
});
var ticket = new AuthenticationTicket(id, props);
context.Validated(ticket);
}
}
tempo Accesso Sto usando questo SimpleAuthorizationServerProvider (in Api Web) posso ricevere e inviare token di accesso al client. Anche in questo caso Accesso utente deve accedere a altre pagine, Come posso convalidare la mia personalizzato token di accesso OAuth2 a lato server (in Api Web)Come posso convalidare la mia personalizzato token di accesso OAuth2 nel lato server
Da lato client Sono gettone generazione come questo
private static TokenResponse GetToken()
{
var client = new OAuth2Client(new Uri("http://localhost:1142/token"), "client1", "secret");
var response = client.RequestResourceOwnerPasswordAsync(uid, pwd).Result;
Console.WriteLine(response.AccessToken);
return response;
}
e call particolare web API dopo l'autenticazione come questa
private static void CallProfile(string token)
{
var client = new HttpClient();
client.SetBearerToken(token);
var response = client.GetStringAsync(new Uri("http://localhost:1142/api/Profile?id=1")).Result;
}
Basta parlare dal mio cappello qui, ma se il token portatore viene restituito nell'intestazione Autorizzazione poi una semplice chiamata a User.Identity.IsAuthenticated dovrebbe dirti se il token è valido o meno. – Mark
@Mark - potrebbe essere, tuttavia, cosa succede quando il metodo viene chiamato tramite una richiesta Ajax e non vi è User.Identity collegato alla richiesta? – Catchops
@Catchops È necessario passare il token nell'intestazione Autorizzazione della richiesta (ad esempio Autorizzazione: Bearer YOUR_TOKEN) quando si effettua la richiesta AJAX. – Mark