Skip to content
This repository has been archived by the owner on May 6, 2021. It is now read-only.

Latest commit

 

History

History
105 lines (79 loc) · 2.77 KB

check-user-login.asciidoc

File metadata and controls

105 lines (79 loc) · 2.77 KB
title order layout
Checking Authentication
95
page

Checking Authentication

Although authorization is defined at endpoint level as described in the Security page, the developer might be interested on knowing specific authentication parameters in Java code, or even what are the user access rights in TypeScript.

Checking Authentication in Server Side

The easiest way to configure authentication is by using Spring Security, thus use it’s API for checking the user in your endpoints. In the next example the username is checked in the Java code:

@Endpoint
public class DrawEndpoint {

    public String checkWinner() {
        Authentication auth =
            SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && "peter".equals(auth.getName())) {
            return "Congrats! you are the winner.";
        }
        return "Sorry, keep looking";
    }
}

Checking Authentication in Client Side

Checking the user name

In TypeScript there is no direct way for checking whether the user is authenticated, nevertheless it’s possible to expose an endpoint in server side checking user privileges and returning the status.

The next example returns the username when in the user is logged-in, or the word 'anonymousUser' otherwise:

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

@Endpoint
public class MyAppEndpoint {

    @AnonymousAllowed
    public String checkUser() {
        Authentication auth =
            SecurityContextHolder.getContext().getAuthentication();
        return auth == null ? null : auth.getName();
    }
}
import * as appEndpoint from '../generated/MyAppEndpoint';

const username = await appEndpoint.checkUser();

if ('anonymousUser' === username) {
   console.log('You are an anonymous user');
} else {
   console.log('Your username is: ' + username);
}

Checking roles

Developer might want to check whether the user can access certain services so as the appropriate options are enabled in the application menu.

The next example exposes a method that can be used to check whether the application is being used by an admin user.

@Endpoint
public class MyAppEndpoint {

    @RolesAllowed("ROLE_ADMIN")
    public boolean isAdmin() {
        return true;
    }
}
import * as appEndpoint from '../generated/MyAppEndpoint';

const isAdmin = await appEndpoint.checkUser().catch(() => false);

if (isAdmin) {
   console.log('You are an admin user');
} else {
   console.log('Sorry, you are not an admin user');
}