Secure AngularJs application with Spring Security

Most of JEE developers are aware of web applications security requirements and are familiar with security frameworks like Spring-Security.

But when we have to secure a web application based on front-end framework like AngularJs, we will have to deal with some specific features and we will need to customize the server-side configuration.

For example, some commonly used features like Spring-Security taglib can’t be used because page is rendered client-side.

Photo credit: SLO Icon Design
In this post, I will present a sample project to deal with some common security features in an AngularJs project.
You can get project source code on GitHub here and you can run the application here.

1 – Back-end security management

This parts provides instructions on how to add Spring Security to an existing application using Spring java based config.

1.1 – Back-end dependencies

In order to use Spring Security you must add the necessary dependencies. For the sample we will add the following Spring Security dependencies:



1.2 – Spring security config

In this step, we create a Spring Security configuration.

@ComponentScan(basePackages = {""})
public class SecurityConfig extends WebSecurityConfigurerAdapter {

 public static final String REMEMBER_ME_KEY = "rememberme_key";

 private RestUnauthorizedEntryPoint restAuthenticationEntryPoint;

 // Autowire other required beans 

 public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

 public void configure(WebSecurity web) throws Exception {
  web.ignoring().antMatchers("/resources/**", "/index.html", "/login.html",
   "/partials/**", "/", "/error/**");

 protected void configure(HttpSecurity http) throws Exception {
    .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())

1.2.1 – Authentication config

Authentication entry point
We need a custom authenticationEntryPoint because default Spring-Security config will redirect to login page. In our case we need just a https status 401 and a json response.

public class RestUnauthorizedEntryPoint implements AuthenticationEntryPoint {

 public void commence(HttpServletRequest request, HttpServletResponse response,
  AuthenticationException exception) throws IOException, ServletException {
  SecurityUtils.sendError(response, exception, HttpServletResponse.SC_UNAUTHORIZED,
   "Authentication failed");

Login success handler
The login success handler returns http status 200 with user info in json format.

public class RestAuthenticationSuccessHandler 
extends SimpleUrlAuthenticationSuccessHandler {

 private UserRepo userService;

 public void onAuthenticationSuccess(HttpServletRequest request, 
  HttpServletResponse response, Authentication authentication)
 throws ServletException, IOException {
  User user = userService.findByLogin(authentication.getName());
  SecurityUtils.sendResponse(response, HttpServletResponse.SC_OK, user);

Login fail handler
The login fail handler returns http status 401.

public class RestAuthenticationFailureHandler
extends SimpleUrlAuthenticationFailureHandler {

 public void onAuthenticationFailure(HttpServletRequest request,
  HttpServletResponse response, AuthenticationException exception)
 throws IOException, ServletException {
  SecurityUtils.sendError(response, exception, HttpServletResponse.SC_UNAUTHORIZED,
   "Authentication failed");

Logout success handler
When logout succeeds, we need to return ok status instead of login page redirection.
Spring security implements logout handler that returns ok status.

Account Rest web service
The account Rest web service returns the authenticated user account information if he’s already authenticated.

public class SeurityController {

 private UserRepo userRepo;

 @RequestMapping(value = "/security/account", method = RequestMethod.GET)
 public @ResponseBody
 User getUserAccount() {
  User user = userRepo.findByLogin(SecurityUtils.getCurrentLogin());
  return user;


1.2.2 – Authorization config

You can manage authorization by specifying authorized roles for each secured URL.

// @other annotations ..
public class SecurityConfig extends WebSecurityConfigurerAdapter {

// extra config code ...

protected void configure(HttpSecurity http) throws Exception {
    // others config ...


Using Spring-Security annotations is another way to manage authorization.

First, we enable method security in the config class

@EnableGlobalMethodSecurity(prePostEnabled = true)
// @other annotations ..
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  // config code ... 

Next, we add annotation for a method that must have access restriction.

public class SeurityController {

    @RequestMapping(value = "/security/tokens", method = RequestMethod.GET)
    public @ResponseBody
    List<Token> getTokens () {
       // method code ...

Access denied handler
The access denied handler returns http status 403.

public class RestAccessDeniedHandler implements AccessDeniedHandler {

 public void handle(HttpServletRequest request, HttpServletResponse response,
  AccessDeniedException exception) throws IOException, ServletException {
  SecurityUtils.sendError(response, exception, HttpServletResponse.SC_FORBIDDEN, 
   "Not authorized resources");

2 – Front-end security management

2.1 – Front-end dependencies

If you are using Bower, you need to add to your bower.json file the dependencies in the code bellow.

  "name": "example",
  "version": "0.0.1",
  "dependencies": {
    "jquery": "2.1.4",
    "angular": "~1.4",
    "angular-route": "~1.4",
    "angular-resource": "~1.4",
    "angular-sanitize": "~1.4",
    "angular-animate": "~1.4",
    "angular-spinkit": "0.3.3",
    "angular-http-auth": "1.2.2",
    // others dependencies

2.2 – AngularJs config

The code source bellow presents the routeProvider configuration.

var myapp = angular
    .module('myApp', ['ngResource', 'ngRoute', 'http-auth-interceptor']);

myapp.config(function ($routeProvider, USER_ROLES) {

    $routeProvider.when("/home", {
        templateUrl: "partials/home.html"      
    }).when('/login', {
        templateUrl: 'partials/login.html',
        controller: 'LoginController'
    }).when("/error/:code", {
        templateUrl: "partials/error.html",
        controller: "ErrorController"
       // Other routes config ...
       // ......
        redirectTo: '/error/404'

2.3 – Authentication management

First, create services.

myapp.service('Session', function () {
    this.create = function (data) { =;
        this.login = data.login;
        this.firstName = data.firstName;
        this.lastName = data.familyName; =;
        this.userRoles = [];
        angular.forEach(data.authorities, function (value, key) {
        }, this.userRoles);
    this.invalidate = function () { = null;
        this.login = null;
        this.firstName = null;
        this.lastName = null; = null;
        this.userRoles = null;
    return this;

myapp.service('AuthSharedService', function($rootScope, $http, authService, Session) {
 return {
  login: function(userName, password, rememberMe) {
   var config = {
    params: {
     username: userName,
     password: password,
     rememberme: rememberMe
    ignoreAuthModule: 'ignoreAuthModule'
   $'authenticate', '', config)
    .success(function(data, status, headers, config) {
    }).error(function(data, status, headers, config) {
     $rootScope.authenticationError = true;

Next, write a login controller.

myapp.controller('LoginController', function($rootScope, $scope, AuthSharedService) {
 $scope.rememberMe = true;
 $scope.login = function() {
  $rootScope.authenticationError = false;
  AuthSharedService.login($scope.username, $scope.password, $scope.rememberMe);

Finally, create login.html partial page.

    <div class="form-group"
         ng-class="{'has-error is-focused' : authenticationError}">
        <input id="login" ng-model="username" type="text" class="form-control" 
               required="required" placeholder="login"/>
        <span ng-show="authenticationError" class="help-block">
            Please check your credentials and try again.

    <div class="form-group">
        <input id="password" ng-model="password" type="password" class="form-control" 
               required="required" placeholder="password"/>

    <input type="checkbox" ng-model="rememberMe"/><span> Remember me</span>

    <button ng-click="login()" >Login</button>

2.4 – Authorization management

In this part, we deal with server-side authorization error and with client-side authorization managing.

2.4.1 Manage server-side authorization

If the requested resource or service isn’t authorized for the authenticated User, the request will fail with response status 403.
The client-side logic must intercept the error and redirect the user to a 403 error page.$rootScope, $location, $http, AuthSharedService, Session,
 USER_ROLES, $q, $timeout) {
// Call when the 403 response is returned by the server
 $rootScope.$on('event:auth-forbidden', function(rejection) {
  $rootScope.$evalAsync(function() {

2.4.2 – Client-side authorization management

It’s better to manage authorization client-side for better performance and to avoid servers-side errors.

We added an access property which details if the route requires the user to be logged in and what permissions the user must have to access the route.

myapp.constant('USER_ROLES', {
    all: '*',
    admin: 'admin',
    user: 'user'

myapp.config(function ($routeProvider, USER_ROLES) {

   $routeProvider.when("/home", {
        templateUrl: "partials/home.html",
        controller: 'HomeController',
        access: {
            loginRequired: true,
            authorizedRoles: [USER_ROLES.all]
    }).when('/users', {
        templateUrl: 'partials/users.html',
        controller: 'UsersController',
        access: {
            loginRequired: true,
            authorizedRoles: [USER_ROLES.admin]
    // other routs config ...
    // ... 
        redirectTo: '/error/404',
        access: {
            loginRequired: false,
            authorizedRoles: [USER_ROLES.all]

Next, we add a service function to check if authenticated user has required roles to access the resource.

myapp.service('AuthSharedService', function (Session) {
    return {
        // other functions ...
        isAuthorized: function (authorizedRoles) {
            if (!angular.isArray(authorizedRoles)) {
                if (authorizedRoles == '*') {
                    return true;
                authorizedRoles = [authorizedRoles];
            var isAuthorized = false;
            angular.forEach(authorizedRoles, function (authorizedRole) {
                var authorized = (!!Session.login &&
                Session.userRoles.indexOf(authorizedRole) !== -1);
                if (authorized || authorizedRole == '*') {
                    isAuthorized = true;
            return isAuthorized;

Finally, we implement a listener on the $routeChangeStart event to track the next route navigation.
– If the user is not yet authenticated the function broadcast “event:auth-loginRequired”.
– If the user is not authorized the function broadcast “event:auth-loginRequired”.$rootScope, AuthSharedService, USER_ROLES) {

 $rootScope.$on('$routeChangeStart', function(event, next) {
 if (next.originalPath === "/login" && $rootScope.authenticated) {
  } else if (next.access && next.access.loginRequired && !$rootScope.authenticated) {
   $rootScope.$broadcast("event:auth-loginRequired", {});
  }else if(next.access && !AuthSharedService.isAuthorized(next.access.authorizedRoles)) {
   $rootScope.$broadcast("event:auth-forbidden", {});


2.4.3 – Manage already authenticated user

If the user is already authenticated and he has a valid remember me token he should access the application to the requested page.

When the application starts running, it requests account Rest web service. If the user is already authenticated the rest API will return user details.

We have to carry about account Rest web service response time. That’s why we redirect the user to loading page until getting the response to check authorities for accessing the requested page.

First, we update the AutehtSharedService with getAccount function.

myapp.service('AuthSharedService', function ($rootScope, $http, $resource, 
    authService, Session) {
    return {
        login: function (userName, password, rememberMe) {
            // login code ...
        getAccount: function () {
            $rootScope.loadingAccount = true;
                .then(function (response) {
        isAuthorized: function (authorizedRoles) {
            // isAuthorized code ..

Next, we add code to handle events and call getAccount function.$rootScope, $location, $http, AuthSharedService, Session,
 USER_ROLES, $q, $timeout) {

 $rootScope.$on('$routeChangeStart', function(event, next) {
  // route change start code ...

 // Call when the the client is confirmed
 $rootScope.$on('event:auth-loginConfirmed', function(event, data) {
  $rootScope.loadingAccount = false;
  var nextLocation = ($rootScope.requestedUrl ? $rootScope.requestedUrl : "/home");
  var delay = ($location.path() === "/loading" ? 1500 : 0);

  $timeout(function() {
   $rootScope.account = Session;
   $rootScope.authenticated = true;
  }, delay);


 // Call when the 401 response is returned by the server
 $rootScope.$on('event:auth-loginRequired', function(event, data) {
  if ($rootScope.loadingAccount && data.status !== 401) {
   $rootScope.requestedUrl = $location.path()
  } else {
   $rootScope.authenticated = false;
   $rootScope.loadingAccount = false;

 $rootScope.$on('event:auth-forbidden', function(rejection) {
  // auth-forbidden code ...

 // Get already authenticated user account


2.5 – Securing UI Elements

To secure UI elements, we will create a directive that accepts as attribute a comma-separated list of authorized roles.

myapp.directive('access', [
    function (AuthSharedService) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                var roles = attrs.access.split(',');
                if (roles.length > 0) {
                    if (AuthSharedService.isAuthorized(roles)) {
                    } else {

Next, we specify authorized roles in the access property.

      <ul class="nav navbar-nav">
            <li><a href="#/home" class="mdi-action-home"></a></li>
            <li><a href="#/users">Users</a></li>
            <li><a href="#/apiDoc">API Doc.</a></li>
            <li><a href="#/tokens" access="admin">Sessions</a></li>


Even if security is managed client-side with all security features, it’s important to manage security server-side.
Client-side security is easy to hack; user can inspect code and change CSS and display hidden elements and it can display network requests and execute them out of the application.

I hope this post helped you to get an overview on securing an Angular web application with Spring Security. For more information you can read source code in Github and run a demo here.

Thanks for your comments🙂


46 thoughts on “Secure AngularJs application with Spring Security

  1. Dear Samer,
    I have cloned your project on GitHub and I faced with lots of errors. After trying to manipulate the Maven to fix issues I ran it on Glassfish server and found the server sill can’t find bean file or any web.xml file. The question is how can I start this project successfully and does every web project need a web.xml file ? I like to work to upgrade this project to spring IDAP but I wasn’t successful unfortunately.

    • Thank you for your comment.
      If your application container is Servlet 3.0 ready you don’t need a web.xml file.
      You have to verify if the glassfish version is Servlet 3.0 ready.
      For pom build errors, can you provide log errors as an issue in Github.
      I will try to fix it.

      • I think the project ran. But I get 404 not found error in debugging with the URL path /security/account
        MY Glassfish server is 4.1 and supports Servlet3 annotations.

  2. Sorry, I found that I didn’t put the source in Java folder. However after restructing the project carefully, I found that org.springframework.orm can not be found. Did you miss something in maven file?

    • I don’t think that I missed some dependencies. The project is built on Linux (Openshift) server, deployed on Jboss, and runs without any problem.

      I did a test with Glassfish server. There is a problem with Guava version. GlassFish loads an older version.

      You can fix it by removing Swagger Rest API documentation, if you don’t need It.

  3. Hi!

    Failed to run task (com.github.eirslett:frontend-maven-plugin:0.0.22:bower:bower install:generate-resources)

    Failed to run task (com.github.eirslett:frontend-maven-plugin:0.0.22:gulp:gulp build:generate-resources)

    Any idea what may cause this? I tried deleting those to executions

    bower install



    gulp build



    and it compiled successfully but unfortunately it didnt load first page cuz there was missing folder ‘vendors’ in resources folder and also some uncaught errors ‘Cannot read property ‘controller’ of undefined’ etc.

    Any idea what may cause this? I am using tomcat 8.

  4. Dear Sameer

    I was looking for good spring security+AngularJs login based application. You work is very nice.
    Actually I am converting my current spring mvc project into AngularJs based. As already lot of code/functionality exist I am dare change the whole existing setup . I am comfort with spring-context.xml and web.xml based (existing projeect setup). Do you have any sample with xml based config.? it will be very helpful for me.
    In your code how we set session invalidate on inactive

    thanks in advance

  5. How secured is this example, since you are disabling the CSRF protection and in this part of the tutorial: “Client-side authorization management” you do the authorization in the client side, is this configuration secured in production?

    • Hi,

      If you think you have CSRF risk, you have to enable protection against it.

      In this sample Authorization is managed server side and client side.
      You can test it by login as “bill” user, then try in the browser to call rest API to provide authenticated users “/security/tokens”. You will get response status 403.
      For your test you can use this URL:

      This configuration is secured in production.


      • I tried adpting the example to my angularjs/spring mvc web app, but I when I press the login button it doesn’t do anything, I beleive that this part it’s not too clear form me:

        In the AuthSharedService service you o a to a url like this
        $‘authenticate’, ”, config)
        .success(function (data, status, headers, config) {
        }).error(function (data, status, headers, config) {
        $rootScope.authenticationError = true;

        the thing is that I don’t understand what does means the ‘authenticate’ url that you put inside the post method like this $‘authenticate’, ”, config), since you only use this ‘authenticate’ value in the class in the .loginProcessingUrl(“/authenticate”) but I don’t have that url in my project and you don’t have it also, since I downloaded your project from github and searched fro that url and it doesn’t appear in any other file besides, the and AuthSharedService.js

        thanks in advance

  6. I have a doubt, couldn’t somebody press F12 in their web browser and then use the console to override the permission level that is set for them on the service? Is there a way to restrict the views in the serve-rside I know that you put this line in the security config in java “.antMatchers(“/users/**”).hasAnyAuthority(“admin”)”but I tried putting the partials like in my case “partials/deleteUser.html” and i put the role admin so the admin would be the only one who could wath the page but it din’t worked I always get the forbiden response even when I try with the role admin, if there a way to protect partials from the server-side? can I tried moving the partials from the resourses folder and put them in the views folders wheres the index.html page, but I get a 404 error

    • Hi Feng,

      Here is my response for your 20 May question:
      In the sample source code, we set the login porocess URL to “authenticate”. It’s the URL that the login form is posted to. If unspecified, it defaults to /login.
      Spring Security framework intercepts that URL and gets login and password parameter, then look for the user details. In our case it will use .

      Here is my response to your 22 May question:
      In the post sample, Rest web services URL are secured. Even if user can get the html he can’t get data.
      When Angular calls the Rest service the server return back a 403 status. Then, the angular-http-auth module will broadcast ‘event:auth-forbidden’. Finally, the user is redirected to the 403 error page.
      I think you can secure static html resources. You may need to define a directory hierarchy for your partials html pages like that:
      partials/public/ for public html pages.
      Partials/private/admin for admin pages.
      Partials/private/user for users pages.
      Then, you secure URLs in your securityConfig class.


      • thanks for the reply friend, I tried what you said about creating a folder structure to protect my partials but I always get error 403 like if my user doesn’t have the role to get access to that partial but I’m extremely sure that the user with I login have that role, here is my project structure

        –Source Packages

        I put this line in my SecuirtyConfig class like you said

        and also this one

        but still I get the 403 error message

        I posted this questions in StackOverFlow with more Details

        thanks in advance

  7. sry for all the question friend, I solved the antmatcher problem it was my mistake I was adding the permission instead of the roles in the UserDetailService when you add all the authorities that is why when the antmatcher was checking my authority I was getting a 403 error, but now I notice that when I refresh the page my spring security session is lost, and when this happens I can get access to all the antmatchers private partials it doesn’t matter what role I have if I refresh the page I get access to all the private partials, here is my code in a stackoverflow question , sry and thanks in advanced

    • Hi,

      It’s strange that you lose session.
      I can’t see what the problem is.

      If your project is not confidential and doesn’t have any business code, you can share your source code on GitHub. Then I will try to look for solution.


      • no is not confidential I would put it in GitHub as soon as I get a chance, but I forget to tell you that I’m not doing anything that has to do with the “remember me” I mean I don’t have the RememberMeServices class that extends AbstractRememberMeServices and nothing that have to do with the remember me function, does this have something to do with keeping the session after refreshing the page, I excluded since I thought that it was only to avoid the login after login out.

  8. Caused by: java.lang.ClassCastException: Cannot cast org.springframework.web.SpringServletContainerInitializer to javax.servlet.ServletContainerInitializer problem javax.servlet-api and spring?

    • This error could be related to your workspace or project configuration.
      I will reply to your firs question, it may help you solve this Exception.

      – I suggest using STS ( as Eclipse version. It has all Spring, Git, maven plugins installed and well configured.
      – To import the project, click on menu File>Import>Check out Maven Project from SCM
      Provide SCM URL
      – Right click on the project and select Run as> maven install
      – Finally Right click on the project and select Run as> run on server> select your tomcat (version 7) or you can use provided TC Server.

  9. hi friend sry that I didn’t upload my project to github, but I created a stackoverflow question with all the code that I have in my project, I have the same thing that you have in the example except the remember me related code, I kinda found out the problem, if I refresh or reload the page I get redirected to logout somehow, and then redirected to the login page, does this have something to do with me don’t having any remember me code, I would apreciate if you can check my AuthSharedService javascript file and look the url that I put in the $ method and my login, and of course the SecurityConfig.class is all in that question that I made, thanks in advance and sry

  10. Hey Samer Abdelkafi, Thanks for posting the tutorial. In POST call to /authenticate username and password been passed as query parameters. On omitting theses query parameter error occurs. Why ?

  11. Hi Samer, very nice tutorial! I have some similar requirements, but instead of $routeProvider, I am using $stateProvider. What changes will i need to make to your tutorial to make it work?

    – Can I add an “access” object to my state object like you to in then when() call on $routeProvider?

    – What would be the code change required in this line: $rootScope.$on(‘$routeChangeStart’, function(event, next)

    – What other changes?


    • I think you can control partial page access with UI-Router the same way it’s done with the default angular router.
      You can add access to states like that:

      $stateProvider.state('contacts', {
        template: '<h1>My Contacts</h1>',
        access: {
                  loginRequired: true,
                  authorizedRoles: [USER_ROLES.admin]

      Next you control access on stateChangeStart event.

      function(event, toState, toParams, fromState, fromParams, options){ ... })


  12. Hi Samer;
    i see your powerfull example project and i would like to my project.
    when i am trying to login, i become a failure like ” No ‘Access-Control-Allow-Origin’ header is present ”
    please can you help me?
    Best Regards

  13. Hi Samer Abdelkafi,
    thank you for you nice demo. I really like it. After downloading, it took me an hour for configurations. But i can not build this project.
    i am using nodejs 2.14.7
    JDK 1.7
    maven 3.2.1
    tomcat 7.0.67
    eclipse Juno
    i got as following log error:
    [ERROR] npm WARN prefer global marked@0.3.5 should be installed with -g
    [ERROR] npm WARN EPACKAGEJSON example@0.0.1 No repository field.
    [ERROR] npm WARN EPACKAGEJSON example@0.0.1 No license field.
    [ERROR] bower jquery#2.1.4 ENOGIT git is not installed or not in the PATH
    [ERROR] Failed to execute goal com.github.eirslett:frontend-maven-plugin:0.0.22:bower (bower install) on project ssng-project: Failed to run task: ‘bower install’ failed. (error code 1) -> [Help 1]

    do you any suggestions? highly appreciate if you have any🙂 thank you a lot

      • Hi Samer,

        It is impressed me, it works to me, so great. Thank you for your response and have a nice day

      • Hi

        I did what mentioned, remove frontend-maven-plugin , maven, clean, install, and the error is gone.
        but i cannot start the page, it only shows “404 – Not Found”
        I don’t see any errors, “Clean succesfull” && “Build successful”
        I’m Using wildfly 10, this is the output of the deploy:
        22:37:08,328 INFO [] (DeploymentScanner-threads – 2) WFLYDS0004: Found ssng-project-1.0-SNAPSHOT.war in deployment directory. To trigger deployment create a file called ssng-project-1.0-SNAPSHOT.war.dodeploy
        22:37:08,333 INFO [] (MSC service thread 1-3) WFLYSRV0027: Starting deployment of “ssng-project-1.0-SNAPSHOT.war” (runtime-name: “ssng-project-1.0-SNAPSHOT.war”)

      • Hi, great article!

        i’ve spent some time trying to get this work, i’m still stuck, it seems really hard to do.

        I’m doing

        -Eclipse STS, downloaded code from SCM Provide SCM
        -remove frontend-maven-plugin
        -mvn clean, install, run on Server (wildfly 10)

        It compiles and install OK.

        I deployed, ok I think
        But it returns “404-not found” on the browser =(

        Did this have happened to someone?

        In the wildfly log i see three warnings, i dunno if they are critical or not, since they are warnings:

        WARN [] (MSC service thread 1-4) WFLYEE0007: Not installing optional component org.springframework.http.server.ServletServerHttpAsyncRequestControl due to an exception (enable DEBUG log level to see the cause)
        WARN [] (MSC service thread 1-4) WFLYEE0007: Not installing optional component org.springframework.web.context.request.async.StandardServletAsyncWebRequest due to an exception (enable DEBUG log level to see the cause)
        WARN [org.jboss.weld.deployer] (MSC service thread 1-4) WFLYWELD0013: Deployment deployment “ssng-project-1.0-SNAPSHOT.war” contains CDI annotations but no bean archive was not found. (No beans.xml nor class with bean defining annotations)


      • [SOLVED]

        Hi again !!!

        It turns out that the war name was “ssng-project-1.0-SNAPSHOT.war”

        then the “ssng-project” was not the real URL (the one wich pop ups in the browser):

        I changed to ssng-project-1.0-SNAPSHOT and worked perfectly!!

        I think the problem i had is related to the way the war is created i’ll see what is going out with that!


  14. Hello!

    I have a little doubt about your post: Secure AngularJs application with Spring Security.

    When you do a call to /authenticate: $‘authenticate’, ”, config)
    In this way angular sends the post with params as a query string. Is there a way to not do it like this? It seems insecure to me to send credentials data like that. I also tried to send the parameters in the body but spring security is not able to catch them, only works with the parameters as a query string.

    Do you know why it works like that? And do you have a solution to send those params in the post body?

    Thanks in advance, very nice article and the only one I found on the internet that’s actually clear how to combine angularjs and spring security.

    • Hi,

      Thank you for this details and your comment.

      You are right. this is a security problem.

      You can fix it:

      login: function (userName, password, rememberMe) {
                  var config = {
                      ignoreAuthModule: 'ignoreAuthModule',
                      headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                  $'authenticate', $.param({
                          username: userName,
                          password: password,
                          rememberme: rememberMe
                      }), config)
                      .success(function (data, status, headers, config) {
                      }).error(function (data, status, headers, config) {
                      $rootScope.authenticationError = true;

      Best regards

  15. Hi. Thank you for your article. I have chosen your solution for my web project and tell me please. When I try make some changes in your project, it doesn’t allow to do it. For example I tried to change index.html, but after compire the index.html is reverted. Please could you help me? Thanx!

    • Hi,

      The project uses gulp-inject for injecting css and js.

      If you made some changes to css or js imports they will be erased.

      But if you made changes outside of inject:css and inject:js they should be preserved.

      Best regards.

  16. Hi,

    thanks for your work, I really appreciated.

    I got a question: I’ve replicated this behavior in my own project. What I mean is that everything is just like you have architected but my app is a bit different. For example I use “state” instead of “route” provider. And I use mysql instead of hsql. But in the end, 90% is just like your own (cloned from your github).

    So, my question is: why is my app not “landing” on /login url? I mean: I deploy app on tomcat 7 (local eclipse) and when I insert “localhost:8080/myapp/” it will redirect to “otherwise” url (defined in app.js). Even if I’m not actually logged in.
    NOTE: if I go to localhost:8080/myapp/#/login/ I can use the login form correctly, but I get another error (see below).

    Last question: inside authSharedService.js, “login” function. Could you provide an implementation of “authenticate” method? Apparently I can’t logging in if I leave it void.

    Kind regards,

    • [SOLVED] I was ant matching for “/**” instead of “/”. Now everything works fine.

      Just last question: when I successfully login, I expect to be redirect to “/myCustomUrl”. It really redirect me, but it does not replace the content inside “ui-view” (I actually see correct url in top of my browser, but it still display my login form, instead of my “myCustomUrl” content).

      It is angular or spring issue?

      • well….solved this too! It was an improper use of “$location.path(nextLocation).replace()” since I use $state insted of $route. Indeed, the correct way:

        replace –> $location.path(nextLocation).replace()
        with –> $state.go(nextLocation);

        And do it for every $location replace() statement.

  17. Hi,

    new error here: after login, every URL coming from requestMapping (ie: “/security/account”) return a 403 forbidden –> Access denied. Before login it returns 401 (as expected).

    I don’t understand what’s wrong. Same as your application. Maybe the issue is related to spring 4? I’m using 4.3.3


    • solved!😀
      I just added my .antMatchers(“/api”).hasAnyAuthority(“admin”) after the first one with “permitAll()”. In this way, everything works fine. If I add after another “hasAnyAuthority()”, it doesn’t work.
      No guide will explain this, keep in mind: the order is important

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s