8

AngularJS + Spring remembers me feature

 2 years ago
source link: https://www.codesd.com/item/angularjs-spring-remembers-me-feature.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

AngularJS + Spring remembers me feature

advertisements

I'm doing application which is build on spring boot + Angularjs Authentication I did according to this blog post: https://spring.io/guides/tutorials/spring-security-and-angular-js/ So I got basic user/password or OAuth2 enabled

I would like to add Remmeber me functionality to it. I have AuthService

AuthService.authenticate = function (credentials, callback) {
    var headers = credentials ? {
        authorization: "Basic "
        + btoa(credentials.username + ":" + credentials.password)
    } : {};

    $http.get('api/user/', {headers: headers}, {timeout: 5000}).then(
        function (response) {
            var data = response.data;
            if (data.id) {
                $rootScope.authenticated = true;
                $rootScope.principal = data;
                $translate.use($rootScope.principal.language);
                $location.search('lang', $rootScope.principal.language);
                AvatarService.getUserAvatar($rootScope.principal);
                $log.debug("[DEBUG] User logged in " + $rootScope.principal.id);
            } else {
                $rootScope.authenticated = false;
            }
            callback && callback();
        },
        function () {
            $rootScope.authenticated = false;
            callback && callback();
        });
};

And in login controller I got it handled with :

$scope.credentials = {};
//LOGIN
$scope.login = function () {
    AuthService.authenticate($scope.credentials, function () {
        if ($rootScope.authenticated) {
            $location.path("/");
            AlertService.clearAlerts();
        } else {
            $location.path("/login");
            AlertService.addError('user.login.failed');
        }
    });
};

On Spring security I got it set as usually I was setting it, ( part of config)

            ....
            .and().formLogin()
                .loginPage("/#/login")
                .and().rememberMe()
                .rememberMeServices(rememberMeServices())
                .key("remember-me-key")
            .and().addFilterBefore(new CsrfHeaderFilter(), CsrfFilter.class)
                .csrf()
            ....

but my guess is it expect post call with remember-me and not basic auth

How can it be tweaked to be able to use remember me ? Can I just execute call via post to login with j_username j_password and remember-me ?


You can config spring boot server to issue an auth token back to the client. In the client side(Angular), save the token somewhere(local storage/cookie). Then you can check the existence of the token when app first loads. JWT tokens are really good when dealing with web client authentications.

For example, if I have this block of code in my security configuration file.

.authorizeRequests()
    .antMatchers("/", "/index.html", "/login.html", "/home.html").permitAll()
.anyRequest()
.authenticated().and()
.formLogin()
    .successHandler(authenticationSuccessHandler)
    .failureHandler(authenticationFailureHandler)

I can easily implement the authenticationSuccessHandler and issue an auth token, or an auth cookie, or both back to the user upon successful logins.

public class AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

... bla bla bla

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication ) throws IOException, ServletException {
    clearAuthenticationAttributes(request);
    User user = (User)authentication.getPrincipal();

    String jws = tokenHelper.generateToken( user.getUsername() );

    // cookie in response
    Cookie authCookie = new Cookie( TOKEN_COOKIE, ( jws ) );
    authCookie.setPath( "/" );
    authCookie.setHttpOnly( true );
    authCookie.setMaxAge( EXPIRES_IN );
    response.addCookie( authCookie );
    // token in response
    UserTokenState userTokenState = new UserTokenState(jws, EXPIRES_IN);
    String jwtResponse = objectMapper.writeValueAsString( userTokenState );
    response.setContentType("application/json");
    response.getWriter().write( jwtResponse );
}

More detail can be found in springboot-jwt-starter. This is a starter-kit project using spring boot and AngularJS.

The The Login Page: Angular JS and Spring Security Part II series is a very good reading material if you want to implement Spring boot security with Angular.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK