Alexander
Alexander

Reputation: 113

Spring Boot security for rest

I know there are a lot of topics on that but is there any way just modify the normal spring security to work with json objects.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //za pre i post authorize v servisa
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter
{
    //Koi service shte polzvame
    @Autowired
    private UserService userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.authorizeRequests()
                .antMatchers("/", "/user/register", "/css/**", "/js/**").permitAll()
                .antMatchers("/user/user").access("hasRole('USER') or hasRole('ADMIN')")
                .antMatchers("/user/admin").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/user/login").permitAll()
                .usernameParameter("username")
                .passwordParameter("password")
                .and()
                .rememberMe().rememberMeCookieName("RememberMeFromLecture")
                .rememberMeParameter("remember")
                .key("golqmaTaina")
                .and()
                .logout().logoutSuccessUrl("/user/login?logout").logoutRequestMatcher(new AntPathRequestMatcher("/signout")).permitAll()
                .and()
                .exceptionHandling().accessDeniedPage("/user/unauthorized")
                .and().csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(this.userService).passwordEncoder(getBCryptPasswordEncoder());
    }

    @Bean
    public BCryptPasswordEncoder getBCryptPasswordEncoder()
    {
        return new BCryptPasswordEncoder();
    }

}

This is my config file and it works perfectly without rest, but my problem is just want to make the login page to work with rest that's all. If it's configed like this, my login is been done automatically I can't even set a break point inside my controllers. It works, but i want to make it work with rest.

Upvotes: 1

Views: 63

Answers (1)

ManishSingh
ManishSingh

Reputation: 1944

I created a sample application (https://github.com/manishsingh27/TokenBasedAuth) and it is based on REST for authentication. Client application is based on AngularJS and it has login page, files are here - https://github.com/manishsingh27/TokenBasedAuth/tree/main/authz/src/main/resources/static. And REST APIs are present here - https://github.com/manishsingh27/TokenBasedAuth/blob/main/authz/src/main/java/com/adms/authz/self/user/controller/UsersController.java. Config file is here -https://github.com/manishsingh27/TokenBasedAuth/blob/main/authz/src/main/java/com/adms/authz/config/SecurityConfiguration.java
You need to use the @EnableResourceServer annotation to secure the Rest APIs.

Upvotes: 1

Related Questions