Introduction
In this tutorial, we will discuss how to implement authentication and authorization in a Java Spring application using OAuth with Spring Security. We will cover concepts such as token-based authentication, securing endpoints, and user roles.
1. Setting up OAuth2 Configuration
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client-id")
.secret("client-secret")
.authorizedGrantTypes("password", "authorization_code", "refresh_token")
.scopes("read", "write");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
}
2. Securing Endpoints
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/**").authenticated()
.antMatchers("/admin/**").hasRole("ADMIN");
}
}
3. Custom UserDetailsService
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) {
// Fetch user from database
// Create UserDetails object
return new User(username, password, authorities);
}
}
4. User Authentication
@RestController
public class UserController {
@Autowired
private AuthenticationManager authenticationManager;
@PostMapping("/login")
public ResponseEntity login(@RequestBody LoginRequest request) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
return ResponseEntity.ok("Logged in successfully!");
}
}
Conclusion
In this tutorial, we have covered the basics of implementing authentication and authorization in a Java Spring application using OAuth with Spring Security. By following these steps, you can secure your application and control access to different endpoints based on user roles.