Quantcast
Channel: Blog – Stormpath User Identity API
Viewing all articles
Browse latest Browse all 278

Tips and Tricks for AngularJS and Spring Boot with Stormpath

$
0
0

In October, I showed you how to integrate AngularJS, Spring Boot, and Stormpath. As part of that tutorial, I demonstrated how to use our AngularJS SDK to create registration, login and forgot password screen. I also showed how to configure Spring Boot to allow cross-domain requests.

Today, I’ll show you how to 1) restrict access to functionality with our AngularJS SDK and 2) use our Spring Boot Starter v1.2.0 to simplify HTTP access control (CORS). Restricting access allows you to show different sections of your UI to different sets of users. With our CORS configuration, the console error you get when logging out goes away. Taken together, these tips can increase security and improve the user experience for your application.

Restrict Access with Stormpath’s AngularJS SDK

Stormpath’s AngularJS SDK can be used to prevent access to certain states and hide links for different groups. On the Java side, you can use Spring Security to control access by group membership. To begin, clone the project I created for the last tutorial:

git clone https://github.com/stormpath/stormpath-angularjs-spring-boot-example.git \
stormpath-angularjs-access-control-cors-example

To run the Spring Boot backend, execute mvn spring-boot:run. To run the AngularJS frontend, in another terminal window, execute npm install && gulp.

In the last tutorial, I showed how you can use if-user and if-not-user directives to show/hide elements when users are logged in/logged out.

In addition, you can protect states in their ui-router configuration. For example, “view2” and “search” are not protected, so it should be possible to navigate to them directly with http://localhost:3000/view2 and http://localhost:3000/search. However, when you try these, you’ll see an error in your browser.

Cannot GET /view2/

This is not caused by Angular or Stormpath, but rather Browsersync’s configuration. It’s not configured to work with AngularJS when it’s in HTML5 mode. The good news is it’s easy to fix.

First, install connect-history-api-fallback.

npm install connect-history-api-fallback --save-dev

Then modify gulpfile.js to import it and change Browsersync to use it.

var historyApiFallback = require('connect-history-api-fallback');
...
gulp.task('serve', function() {

    browserSync.init({
        server: {
          baseDir: './app',
          middleware: [ historyApiFallback() ]
        }
    });

After making these changes, you can navigate to http://localhost:3000/view2 or http://localhost:3000/search.

view2 unprotected

search unprotected

Using Stormpath’s AngularJS SDK, configure “view2” so it requires the user to be authenticated and make it so “search” can only be accessed by users in the “ADMIN” group. But first, upgrade to the latest version by running:

bower install

Open app/view2/view2.js and use Stormpath’s State Config to ensure the user is authenticated.

.config(['$stateProvider', function($stateProvider) {
  $stateProvider.state('view2', {
    url: '/view2',
    templateUrl: 'view2/view2.html',
    controller: 'View2Ctrl',
    sp: {
      authenticate: true
    }
  });
}])

After making this change, when you try to navigate to http://localhost:3000/view2, you’ll be redirected to login. If it works, good job!

To limit the “search” state to the “admin” group, modify app/search/search.state.js:

function stateConfig($stateProvider) {
  $stateProvider
    .state('search', {
      url: '/search',
      templateUrl: 'search/search.html',
      controller: 'SearchController',
      controllerAs: 'vm',
      sp: {
        authorize: {
          group: 'admin'
        }
      }
    });
}

TIP: You can also use the data.authorities to specify groups. We added support for this configuration because this is the configuration that JHipster expects. It also allows you to configure multiple groups.

function stateConfig($stateProvider) {
  $stateProvider
    .state('search', {
      url: '/search',
      templateUrl: 'search/search.html',
      controller: 'SearchController',
      controllerAs: 'vm',
      data: {
        authorities: ['admin']
      }
    });
}

After making this change, you’ll need to perform two additional tasks to make it work. First, you’ll need to create a group named “admin” in the admin console. The abbreviated steps are as follows:

  1. Create a new Application
  2. Create a new Group called “admin” for the Application
  3. Create a new Account in the admin Group
  4. Create a new Account NOT in the admin Group

Click here for a visual walkthrough of this process.

Next, you’ll need to configure Spring Boot to show group information when calling the /me endpoint. Modify src/main/resources/application.properties to expand groups.

stormpath.web.me.expand.groups = true

Also, modify pom.xml so you’re using the latest release of Stormpath’s Spring Boot support.

...
    
        org.springframework.boot
        spring-boot-starter-parent
        1.4.2.RELEASE
        
    
...
        
            com.stormpath.spring
            stormpath-default-spring-boot-starter
            1.2.1
        
...

Spring Boot’s developer tools and Browsersync will restart everything for you. If you see the following error in your browser console, restart Spring Boot manually.

TypeError: Cannot read property 'filter' of undefined

Now if you try to navigate to http://localhost:3000/search as a non-admin user, you won’t be able to. If you login as an admin user, you’ll be able to see the screen. If you’d like to alert the user that they’ve been denied access to this state, you can use something like the following:

$scope.$on('$stateChangeUnauthorized', function () {
  $state.go('accessdenied');
});

Of course, you’ll need to define the accessdenied state for this to work.

The final step is to hide the “search” link for non-admin users. Open app/index.html and change the list item for the search link to the following:

  • search
  • Now that you’ve learned how to control access with AngularJS and Stormpath, let’s look at simplifying the CORS configuration for Spring Boot.

    Easy CORS Configuration with Stormpath’s Spring Boot Starter

    Stormpath Java SDK v1.2.0 adds support for CORS entirely by configuration using the following properties.

    stormpath.web.cors.enabled
    stormpath.web.cors.allowed.originUris
    stormpath.web.cors.allowed.headers
    stormpath.web.cors.allowed.methods

    You can see their default settings in web.stormpath.properties.

    The only property you need to override is stormpath.web.cors.allowed.originUris, because it’s blank by default. Add this property to src/main/resources/application.properties and set it to http://localhost:3000. Remove stormpath.web.stormpathFilter.order=1, while you’re in there.

    spring.data.rest.basePath=/api
    stormpath.web.me.expand.groups = true
    stormpath.web.cors.allowed.originUris = http://localhost:3000

    In addition, remove the corsFilter bean defined in src/main/java/com/example/SecurityConfiguration.java.

    Along with simplifying CORS configuration, this also solves an issue that the previous Spring-based configuration had, where clicking the Logout link displayed an error in the browser console.

    logout cors error

    Learn More about AngularJS and Stormpath

    This article showed you how to limit access to states and hide sections of your AngularJS UI with Stormpath’s AngularJS SDK. It also showed you how the 1.2.0 release of our Java SDK greatly simplifies CORS configuration.

    You can find the source code for this example application on GitHub. You can read the following commits to see how each section is implemented.

    1. Make Browsersync work with AngularJS’s HTML5 mode
    2. Limit access to states and hide links with Stormpath’s AngularJS SDK
    3. Easy CORS configuration for Spring Boot

    If you’d like to see more tips and tricks with Stormpath’s AngularJS or Java SDKs, please let me know in the comments below.

    Related:

    The post Tips and Tricks for AngularJS and Spring Boot with Stormpath appeared first on Stormpath User Identity API.


    Viewing all articles
    Browse latest Browse all 278

    Trending Articles