PRITAM MOHAPATRA
PRITAM MOHAPATRA

Reputation: 98

spring security add Granted autherity

I got some code from Internet.
Here is it:

     public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        CustomerBean customerBean = customerService.getCustomerBeanByEmail(userName);
        if (customerBean == null) {
            throw new UsernameNotFoundException("Invalid username or password");
        } else if(!CustomerStatus.ACTIVATED.equals(customerBean.getStatus())) {
            throw new LockedException("User account is locked");
        }
        return createCustomer(customerBean);
    }

    public void signIn(CustomerBean customer) {
        SecurityContextHolder.getContext().setAuthentication(authenticate(customer));
    }

    private Authentication authenticate(CustomerBean customerBean) {
        return new UsernamePasswordAuthenticationToken(createCustomer(customerBean), customerBean.getPassword(), createAuthority());
    }

    private User createCustomer(CustomerBean customerBean) {
        return new CustomerDetailsImpl(customerBean, createAuthority());
    }

    private Set<GrantedAuthority> createAuthority() {
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        return grantedAuthorities;
    }
and my Configure method

     public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customerDetailsServiceImpl).passwordEncoder(new ShaPasswordEncoder(256));
    }
@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/resources/**").permitAll()
        .antMatchers("/app/**").permitAll()
        .antMatchers("/403").permitAll()

        .anyRequest().authenticated()
    .and()
        .formLogin()
            .loginPage("/login").permitAll()
            .failureUrl("/loginError")
            .defaultSuccessUrl("/app/home", true)
    .and()
        .logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl("/logoutUser")
            .permitAll()
            .invalidateHttpSession(true)
            .deleteCookies("JSESSIONID")
    .and()
        .exceptionHandling().accessDeniedPage("/403")
    .and()
        .csrf().disable();
}

My question is: how to add the role to specific url?
Like has_user, has_admin what to add in code?

Upvotes: 0

Views: 72

Answers (1)

Matthias
Matthias

Reputation: 1448

You can add the required roles for specific urls in the authorizeRequests section at the beginning of configure(HttpSecurity http) like

.antMatchers("/your/user/**").hasRole("user")
.antMatchers("/your/admin/url").hasRole("admin")

Upvotes: 1

Related Questions