我正在尝试使用WebApi 2,使用Angular 8 CRUD和WebAPI中的OAuth2.0来设置OAuth登录(https://www.c-sharpcorner.com/article/angular-8-crud-with-oauth2-0-in-webapi-part-2/)。
我已经剪切并粘贴了他的代码,但是我得到了:
400(错误请求)错误:“ unsupported_grant_type”
[当我使用http://localhost/oauth/token打回我的Visual Studio 2015 IIS Express实例时>
我浏览了十几篇文章,所有文章都包含了application / x-www-urlencoded的content-type标头,我已经完成了,但我仍然无法使这血腥的事情起作用!
他的用户身份验证是一项服务,如下所示:
import {HttpClient,HttpHeaders} from '@angular/common/http'; import { ProductDTO } from '../app/ProductDTO'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ProductService { ApiUrl='http://localhost:57046/'; constructor(private httpclient: HttpClient) { } UserAuthentication(UserName: string,Password: string):Observable<any>{ let credentials='username=' +UserName + '&password=' +Password +'&grant_type=password'; var reqHeader = new HttpHeaders({'Content-Type': 'application/x-www-urlencoded','No-Auth':'True' }); return this.httpclient.post<any>(this.ApiUrl+'token',encodeURI(credentials),{headers:reqHeader}); } }
接收OAuth请求的后端为:
public class UtiliAuthProvider : OAuthAuthorizationServerProvider { private const string IPW = "invalid_password"; private const string IPWC = "invalid_password_recaptcha"; public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { string clientId; string clientSecret; string jwtName = context.Parameters.Get(ConfigurationManager.AppSettings["WebJWTName"]); if (!context.TryGetBasicCredentials(out clientId, out clientSecret)) { context.TryGetFormCredentials(out clientId, out clientSecret); } if (context.ClientId == null || jwtName.Equals(ConfigurationManager.AppSettings["WebJWTProg"])) { context.Validated(ConfigurationManager.AppSettings["AudienceId"]); } else { if (context.ClientId == null) { context.SetError("invalid_clientId", "client_Id is not set"); } else { if (AudienceProvider.FindAudience(context.ClientId) == null) { context.SetError("invalid_clientId", $"Invalid client_id '{context.ClientId}'"); } else { context.Validated(); } } } return Task.FromResult<object>(null); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { ConfigurationManager.AppSettings["CORSUrl"] }); ApplicationUserManager userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); UtiliUserModel user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { UtiliUserModel failUser = await userManager.FindByNameAsync(context.UserName); if (failUser == null) { context.SetError("user_not_found", "Please check your user name and try again."); return; } await userManager.AccessFailedAsync(failUser.Id); if (await userManager.IsLockedOutAsync(failUser.Id)) { ContextSetErrorLockOut(context); return; } int attemptsLeft = userManager.MaxFailedAccessAttemptsBeforeLockout - failUser.AccessFailedCount; context.SetError(attemptsLeft == 1 ? IPWC : IPW, $"Incorrect password. You have {attemptsLeft} attempt{(attemptsLeft > 1 ? "s" : "")} left before account is locked out."); return; } if (await userManager.IsLockedOutAsync(user.Id)) { ContextSetErrorLockOut(context); return; } if (user.AccessFailedCount > 0) await userManager.ResetAccessFailedCountAsync(user.Id); IFormCollection formData = await context.Request.ReadFormAsync(); ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT"); oAuthIdentity.AddClaim(new Claim(ConfigurationManager.AppSettings["WebJWTName"], formData[ConfigurationManager.AppSettings["WebJWTName"]])); oAuthIdentity.AddClaim(new Claim(ConfigurationManager.AppSettings["ScopeClaim"], new UtiliportalViews(null).IsCurrentRoleAnyAdmin(context.UserName) ? ConfigurationManager.AppSettings["ScopeClaimAdmin"] : ConfigurationManager.AppSettings["ScopeClaimUser"])); context.Validated(new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties(new Dictionary<string, string> {{ UtiliportalDbConstants.AudiencePropertyKey, context.ClientId ?? string.Empty }}))); } private static void ContextSetErrorLockOut(OAuthGrantResourceOwnerCredentialsContext context) { context.SetError("locked_out", "This account has been locked."); } }
该后端已经使用了多年,目前的AngularJS客户端没有任何问题。现在尝试将站点重写为Angular 8,这会造成废话。
有人可以发布一个使用Visual Studio IIS Express服务器如何调用OAuth / WebApi 2.0登录令牌的工作示例。
我正在尝试使用WebApi 2在WebAPI中使用OAuth2.0和Angular 8 CRUD来设置OAuth登录(https://www.c-sharpcorner.com/article/angular-8-crud-with- oauth2-0-in-webapi-part-2 /)中的文章。我...
以下代码将具有客户端ID和密码的oAuth 2密码授予类型发送到使用OpenIddict库配置了JWT令牌的dotnet core 3服务器。