How to create a new Authority Permalink to "How to create a new Authority"

Tip submitted by @Tonterias

Let’s say that you need a new authority besides the given ones of ADMIN and USER. Let the new authority be called ROLE_EXAMPLE_AUTHORITY.

Modify AuthoritiesConstants.java file to include your new authority/authorities:

/**
 * Constants for Spring Security authorities.
 */
public final class AuthoritiesConstants {

    public static final String ADMIN = "ROLE_ADMIN";

    public static final String USER = "ROLE_USER";

    public static final String ANONYMOUS = "ROLE_ANONYMOUS";
    
    public static final String EXAMPLE_AUTHORITY = "ROLE_EXAMPLE_AUTHORITY";

    private AuthoritiesConstants() {
    }
}

Do not forget to include your new role in your authority.csv:

name
ROLE_ADMIN
ROLE_USER
ROLE_ANONYMOUS
ROLE_EXAMPLE_AUTHORITY

With that, you will be able to use it in your SecurityConfiguration.java:

@Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .csrf()
            .disable()
            ...
        ...
        .and()
            .authorizeRequests()
            ...
            .antMatchers("/newresource/**").hasAuthority(AuthoritiesConstants.ROLE_EXAMPLE_AUTHORITY)

And in your Controller layer (e.g. FrontPageConfigResource.java):

@DeleteMapping("/order-items/{id}")
@Timed
@PreAuthorize("hasAuthority('ROLE_EXAMPLE_AUTHORITY')")
public ResponseEntity<Void> deleteOrderItem(@PathVariable Long id) {
    ...
}

And in your Angular html files: jhiHasAnyAuthority=[‘ROLE_ADMIN’, ‘ROLE_EXAMPLE_AUTHORITY’ ...]

And in your Angular routes:

export const messageRoute: Routes = [
    {
        path: 'message',
        component: MessageComponent,
        data: {
            authorities: ['ROLE_EXAMPLE_AUTHORITY'],
            pageTitle: 'Messages'
        },
        canActivate: [UserRouteAccessService]
    }
];

The open-source example is at JhipsterPress: https://github.com/Tonterias/JhipsterPress