Получение неверного пароля при использовании аутентификации токена Web API из Angular 7 TS в .Net Owin - PullRequest
0 голосов
/ 29 апреля 2019

Я использую Angular 7 .i, отправляя данные токена с именем пользователя и паролем на сервер (.net), но OAuthGrantResourceOwnerCredentialsContext получает неверный пароль (не полный)

Мой пароль содержит '&' последний, и я получаю толькополовина пароля до '&', потому что он обрезает его на '&' char

Например, если отправлено '123 & 123abc', я получу только '123' в контексте y.Password.

Я могу найти способ отправить мой пароль с символом '&'.

Что я делаю неправильно, как отправить пароль с символом '&' с ts на контроллер токена .net?

Мойts code

     public login(username: string, password: string): Observable<UserLoginClaims> {
          //password='123&123abc';
 const tokenData = 'username=' + username + '&password=' + password + '&grant_type=password';
            const tokenHeaders: HttpHeaders = new HttpHeaders({ 'Content-Type': 'application/x-www-urlencoded', 'No-Auth': 'True' });

            return this.httpClient.post<UserPzToken>('http://localhost:10392/token', tokenData, { headers: tokenHeaders }).pipe(
              concatMap((userPzToken: UserPzToken) => {
                if (this.localStorageService.setItem('UserPzToken', userPzToken)) {
                  this.UserLogged = true;
                }
                return this.apiService.getItem<UserLoginClaims>('http://localhost:10392/Auth/GetUserClaims').pipe(
                  tap((userLoginClaims: UserLoginClaims) => this.localStorageService.setItem('UserLoginClaims', userLoginClaims))
                );
              }),
              catchError(this.errorHandleService.handleError)
            );
          }

Мой класс запуска c #

 public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888

            //Enable Cors with OWin.
            app.UseCors(CorsOptions.AllowAll);

            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                // Path at the url to get the token
                TokenEndpointPath = new PathString("/token"),
                // The provider we built.
                Provider = new ApplicationOAuthProvider(),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(24),
                AllowInsecureHttp = true,
            };

            app.Use<OwinExceptionHandlerMiddleware>();

            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }



    public class OwinExceptionHandlerMiddleware : OwinMiddleware
    {
        public OwinExceptionHandlerMiddleware(OwinMiddleware next) : base(next) { }





        public async override Task Invoke(IOwinContext context)
        {
            try
            {
                await Next.Invoke(context);
            }
            catch (Exception ex)
            {
                try
                {
                    if (ex is UserAuthException)
                    {
                        //context.Set
                        context.Response.StatusCode = 422; // Status422U nprocessable Entity
                        context.Response.ReasonPhrase = (ex as UserAuthException).ToString();
                        context.Response.ContentType = "application/json";
                    }
                    else
                    {
                        context.Response.StatusCode = 500;
                        context.Response.ReasonPhrase = "Internal Server Error";
                        Logger.Error(ex);
                    }
                }
                catch (Exception innerEx)
                {
                    Logger.Error(innerEx);
                    throw ex;
                }

            }
        }

        private void HandleException(Exception ex, IOwinContext context)
        {
            var request = context.Request;

            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.Response.ContentType = "application/json";

        }

    }

Мой класс ApplicationOAuthProvider c #

 public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
        {
            public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
            {
                context.Validated();
            }

            public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {

                string username = context.UserName;
                string password = context.Password;
                 //here password is 123 not 123&abc
              }

Мой класс WebApiConfig

 public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Cors enabled at startup.cs file.
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Filters.Add(new AuthorizeAttribute());     
    }

1 Ответ

0 голосов
/ 01 мая 2019

Я не нашел идеального решения, но у меня есть быстрый и простой способ избежать проблемных символов в пароле.

Я кодирую свой пароль с помощью символа '&', прежде чем отправить его вот так

 btoa(password) 

const tokenData = 'username=' +  btoa(username) + '&password=' + btoa(password) + '&grant_type=password';

и на сервере я его декодирую

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            var Passwordbase64EncodedBytes = System.Convert.FromBase64String(context.Password);
            string password = System.Text.Encoding.UTF8.GetString(Passwordbase64EncodedBytes);
                   ........................
            }
...