logo
down
shadow

angularjs WebAPI authentication project template


angularjs WebAPI authentication project template

Content Index :

angularjs WebAPI authentication project template
Tag : angularjs , By : Yohan Lee
Date : December 01 2020, 05:00 PM

it fixes the issue There are some project template available for example ng.Net.Template,
But Instead of looking for the template I'll recommend you develop your authentication module so that you have full control over it. It is fairly easy to implement, please see the this answer to understand in details : ASP.NET WebApi authentication with AngularJS

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Authentication from Asp.Net Mvc4 Project to Another Asp.Net Webapi Project, backed by SQL Server CE 4


Tag : asp.net-mvc , By : user118656
Date : March 29 2020, 07:55 AM
Hope that helps Ok, after some rest and some logical thinking, I just realized that I had to change the Login method in the AccountController in the MVC project.
I'm not able to provide any code because I'm not on my dev pc, but it's just any authentication code you would use anywhere else. For example using REST authentication or authentication through a WCF service.

AngularJs -.net MVC WebApi Authentication example


Tag : authentication , By : Stone
Date : March 29 2020, 07:55 AM
I wish this help you If you put a cookie in the header on server side AngularJS will send this cookie all time.. U have nothing to do.
If you want to pass the token in Header not in cxookie on Angular side just do this : $httpProvider.defaults.headers.common['X-Auth'] = yourKey; in your config block.
myModule.factory('myHttpInterceptor', function ($q) {
    return function (promise) {
        return promise.then(function (response) {
            // do something on success              
            return response;
        }, function (response) {
            // do something on error
            //check status 401 or 403
            return $q.reject(response);
        });
    };
});
myModule.config(function ($httpProvider) {
    $httpProvider.responseInterceptors.push('myHttpInterceptor');
});

AngularJs ASP.NET WebApi Authentication with Thinktecture


Tag : angularjs , By : user113409
Date : March 29 2020, 07:55 AM
To fix this issue I´m trying to make an AngularJs web that sends login and password to an ASP.NET WebApi backend and login this user with Thinktecture. , Finally, after reading a lot I have this:
In AngularJS:
'use strict';
app.factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {

var serviceBase = 'http://localhost:64346/';
var authServiceFactory = {};

var _authData = localStorageService.get('authorizationData');

var _authentication = {
    isAuth: _authData != null? true : false,
    userName: _authData != null ? _authData.userName : ""
};

var _saveRegistration = function (registration) {

    _logOut();

    return $http.post(serviceBase + 'api/account/register', registration).then(function (response) {
        return response;
    });

};

var _login = function (loginData) {

    var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;

    var deferred = $q.defer();

    $http.post(serviceBase + 'api/authorization', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {

        localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });

        _authentication.isAuth = true;
        _authentication.userName = loginData.userName;

        deferred.resolve(response);

    }).error(function (err, status) {
        _logOut();
        deferred.reject(err);
    });

    return deferred.promise;

};

var _logOut = function () {

    $http.delete(serviceBase + 'api/authorization').success(function() {
        localStorageService.remove('authorizationData');

        _authentication.isAuth = false;
        _authentication.userName = "";
    });
};

var _fillAuthData = function () {

    var authData = localStorageService.get('authorizationData');
    if (authData) {
        _authentication.isAuth = true;
        _authentication.userName = authData.userName;
    }

}

authServiceFactory.saveRegistration = _saveRegistration;
authServiceFactory.login = _login;
authServiceFactory.logOut = _logOut;
authServiceFactory.fillAuthData = _fillAuthData;
authServiceFactory.authentication = _authentication;

return authServiceFactory;
}]);
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Protocols.WSTrust;
using System.IdentityModel.Services;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Security;
using System.Web.Http;
using System.Xml;
using Thinktecture.IdentityModel.Constants;
using Thinktecture.IdentityModel.WSTrust;
using WebApi_AngularJs.Model;

namespace WebApi_AngularJs.Controllers
{
    public class AuthorizationController : ApiController
    {
        // GET: api/Authorization
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/Authorization/5
        [Authorize]
        public string Get(int id)
        {
            return "value";
        }

    // POST: api/Authorization
    public LoginResponse Post([FromBody]Login data)
    {
        var credentials = new ClientCredentials();
        credentials.UserName.UserName = data.UserName;
        credentials.UserName.Password = data.Password;

        ServicePointManager.ServerCertificateValidationCallback = (obj, certificate, chain, errors) => true;

        var claims = GetClaimsFromIdentityServer(data.UserName, data.Password);

        var response = new LoginResponse();
        if (claims != null)
        {
            //All set so now create a SessionSecurityToken
            var token = new SessionSecurityToken(claims)
            {
                IsReferenceMode = true  //this is 
                //important.this is how you say create 
                //the token in reference mode meaning 
                //your session cookie will contain only a 
                //referenceid(which is very small) and 
                //all claims will be stored on the server
            };
            FederatedAuthentication.WSFederationAuthenticationModule.
            SetPrincipalAndWriteSessionToken(token, true);

            response = new LoginResponse { access_token = token.Id , data = "data"};
        }

        return response;
    }

    // PUT: api/Authorization/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE: api/Authorization/
    public void Delete()
    {
        //clear local cookie
        FederatedAuthentication.SessionAuthenticationModule.SignOut();
        FederatedAuthentication.SessionAuthenticationModule.DeleteSessionTokenCookie();
        FederatedAuthentication.WSFederationAuthenticationModule.SignOut(false);
    }

    private ClaimsPrincipal GetClaimsFromIdentityServer(string username, string password)
    {
        const string WS_TRUST_END_POINT = "https://srv:4443/issue/wstrust/mixed/username";
        var factory = new System.ServiceModel.Security.WSTrustChannelFactory
        (new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                                     string.Format(WS_TRUST_END_POINT));
        factory.TrustVersion = TrustVersion.WSTrust13;
        factory.Credentials.UserName.UserName = username;
        factory.Credentials.UserName.Password = password;

        var rst = new System.IdentityModel.Protocols.WSTrust.RequestSecurityToken
        {
            RequestType = RequestTypes.Issue,
            KeyType = KeyTypes.Bearer,
            TokenType = TokenTypes.Saml2TokenProfile11,  
            AppliesTo = new EndpointReference
            ("urn:webapisecurity")
        };
        var st = factory.CreateChannel().Issue(rst);
        var token = st as GenericXmlSecurityToken;
        var handlers = FederatedAuthentication.FederationConfiguration.
        IdentityConfiguration.SecurityTokenHandlers;
        var token = handlers.ReadToken(new XmlTextReader
        (new StringReader(token.TokenXml.OuterXml))) as Saml2SecurityToken;
        var identity = handlers.ValidateToken(token).First();
        var principal = new ClaimsPrincipal(identity);
        return principal;
    }
}
}
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301879
  -->
<configuration>
  <configSections>
    <section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
    <section name="system.identityModel.services" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="ida:FederationMetadataLocation" value="https://srv:4443/FederationMetadata/2007-06/FederationMetadata.xml" />
    <add key="ida:Realm" value="urn:webapisecurity" />
    <add key="ida:AudienceUri" value="urn:webapisecurity" />
    <add key="AppName" value="Web API Security Sample" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <modules>
      <add name="WSFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
      <add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
    </modules>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
  <system.identityModel>
    <identityConfiguration>
      <audienceUris>
        <add value="urn:webapisecurity" />
      </audienceUris>
      <claimsAuthorizationManager type="Thinktecture.IdentityServer.Ofi.AuthorizationManager, Thinktecture.IdentityServer.Ofi, Version=1.0.0.0, Culture=neutral" />
      <claimsAuthenticationManager type="Thinktecture.IdentityServer.Ofi.AuthenticationManager, Thinktecture.IdentityServer.Ofi, Version=1.0.0.0, Culture=neutral" />
      <certificateValidation certificateValidationMode="None" />
      <issuerNameRegistry type="System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        <trustedIssuers>
          <add thumbprint="489116B0FCF14DF66D47AE272C3B9FD867D0E050" />
        </trustedIssuers>
      </issuerNameRegistry>
    </identityConfiguration>
  </system.identityModel>
  <system.identityModel.services>
    <federationConfiguration>
      <cookieHandler requireSsl="false" />
      <wsFederation passiveRedirectEnabled="true" issuer="https://srv:4443/issue/wsfed" realm="urn:webapisecurity" reply="http://localhost:64346/" requireHttps="false" />
    </federationConfiguration>
  </system.identityModel.services>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

AngularJS and OWIN Authentication on WebApi


Tag : angularjs , By : mux
Date : March 29 2020, 07:55 AM
To fix the issue you can do So I found the answer but brace yourself 'coz this one's weird!! I read this article on code project which led me to my Owin Authorisation server's GrantResourceOwnerCredentials method to check for this
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
var header = context.OwinContext.Response.Headers.SingleOrDefault(h => h.Key == "Access-Control-Allow-Origin");
            if (header.Equals(default(KeyValuePair<string, string[]>)))
            {
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            }

Angularjs and WebAPI - Authentication and Authorization


Tag : chash , By : user155548
Date : March 29 2020, 07:55 AM
should help you out Set up your WebAPI libraries to use Windows Authentication. Add your [Authorization] attributes to your controllers. Your startup logic can certainly pull role names from your database and add those roles for use in the [Authorization] attributes on the controllers/methods.
I don't know that I'd do this on a per-username basis though - I'd create some roles (e.g. admin, user) and control those through AD if I was using Windows Auth. I'd then just store the AD group names as my role names.
Related Posts Related QUESTIONS :
  • learning angular, having issues with ng-options
  • Angularjs chat with strange polling
  • jQuery Sparkline in a cell in ng-grid using CellTemplate and Directive
  • AngularJS determine filter in controller
  • ADAL tokens not revoking on logout
  • How to deploy an app using ionic framework to Amazon? (elastic beanstalk prefered)
  • Conditional injection of a service in AngularJS
  • Filtering on object properties not working
  • Angularjs: Sorting not working in ui-grid with CellTemplate data
  • How to put serial number for rows in data table according to pagination
  • Play Application Couldn't be Started
  • Video capture to not show in my gallery on phone
  • Reject from 'response' into 'responseError'
  • Angular $injector vs inject
  • how to Avoid ng-repeat in <tr> for particular <td> - Angular Js?
  • Express route handling / req.body empty on some routes
  • AngularJS - Adding controller files triggering uncaught error
  • Using the browser to navigate back in an angularjs app with ui-router?
  • ngResource query, get and save
  • Open $modal from the service and pass variables to the controller
  • ngClick evaluated against scope instead of isolateScope
  • onEnter and onExit are not called when state is left/activated in angularjs ui router
  • Shared client & server modules with angularjs and pongular
  • Getting the angular app to run when using protractor
  • Angularjs: create a link for download different types of file
  • How to mock chained promises using Jasmine?
  • NodeJS on Heroku: Push rejected, failed to compile Node.js app
  • Ionic / Angular JS calling the next page by passing a value into a funciton
  • AngularJS - Passing select list value to function returning undefined
  • Angular JS Material mdMedia seems to be not working
  • directive does not work in the ons-toolbar
  • AngularJS : Pass variables in service
  • AngularJS - FAQ inside a modal (bug?)
  • Is there a way to reduce the number of references declared in jasmine unit tests
  • How to pre-populate and bind list of checkbox using AngularJS
  • angularjs $http.post results in 501 Unsupported method ('POST')
  • AngularJS: On Change of Parent DropDown Option Also Changes the Dependant Drop Down Options Associated with Other Parent
  • Angular HTML5 mode, Wordpress, Rewrites, Apache and You
  • Using angular js form validations in <form:input> tag
  • AngularJS call common functions in a directive template
  • AngularJS Promise resolved incorrectly
  • properly clearing whole AngularJS ui-grid chart
  • Can not figure out how to store $rootScope in angular.bootstrap
  • animate.css animation within angularjs 1.3 using ngAnimate gives different animations in Firefox
  • Auth0 IE Issue: Unable to get property 'frames' of undefined or null reference
  • Am I misusing directives with too much logic?
  • Use an Angular JS value as a parameter of TWIG "path" function in Symfony 2
  • multiple function on ng-click angularjs
  • Converting $.ajax call to $http call in angular 404 error
  • Making Anglular min/max validation code work for three variables on multiple fields
  • AngularJS: Add attribute, compile directive
  • Angularjs templateUrl file location not found
  • How to execute the function after change page in angularjs?
  • Pass variable to AngularJS directive without isolated scope
  • OAuth, Custom Login, or Both
  • Angular Directive: Isolate Scope & Transclude is true, but HTML in the directive needs to continue to bind to parent
  • Compare objects in angularjs
  • Angularjs: how to properly save a blob pdf file recieved from the server
  • cannot get the attribute of html tag in angular
  • Md-list in md-card is not adjusting
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com