Spring Security doesn't recognize which logged in user - java

I add Spring Security to my Spring Boot application but after, authentication process server doesn't recognize the same user in next request. I use Angular 5 for UI and maybe this issue in UI side may be requested not include cookies. Help me, please understand why Spring Security doesn't recognize user with already logged in.
In web configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/rest/user/login").permitAll();
http.csrf().disable()
.authenticationProvider(authenticationProvider())
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.formLogin()
.permitAll()
.loginProcessingUrl("/rest/user/login")
.usernameParameter("username")
.passwordParameter("password")
.successHandler(logInSuccessHandler)
.failureHandler(authFailureHandler)
.and()
.logout().permitAll()
.logoutRequestMatcher(new AntPathRequestMatcher("/rest/user/logout", "POST"))
.logoutSuccessHandler(logoutHandler)
.and()
.sessionManagement()
.maximumSessions(1);
http.authorizeRequests().anyRequest().authenticated();
}
Session manager is activated .sessionManagement().maximumSessions(1);
And authentication complete successful my UserDetailsService implementation correctly return User object by login and password. But next request to this controller:
#GetMapping("/rest/list")
public RestList list() {
...
}
Redirect to :
#Component
public class UnauthorizedHandler implements AuthenticationEntryPoint {
#Override
public void commence(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
}
}
I have the logged in checker:
#Component
public class LoggedInChecker {
public User getLoggedInUser() {
User user = null;
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
Object principal = authentication.getPrincipal();
// principal can be "anonymousUser" (String)
if (principal instanceof UserDetailsImpl) {
UserDetailsImpl userDetails = (UserDetailsImpl) principal;
user = userDetails.getUser();
}
}
return user;
}
}
I use this checker in UserService
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userRepository;
#Autowired
private LoggedInChecker loggedInChecker;
#Override
public User getUserByUsername(String username) {
return userRepository.findByUsername(username);
}
#Override
public List<String> getPermissions(String username) {
User user = userRepository.findByUsername(username);
return nonNull(user) ? user.getRoles().stream().map(Role::getRole).collect(toList()) : Lists.newArrayList();
}
#Override
public User getCurrentUser() {
return loggedInChecker.getLoggedInUser();
}
#Override
public Boolean isCurrentUserLoggedIn() {
// This place must call but nothing happening
return nonNull(loggedInChecker.getLoggedInUser());
}
}
I thought Spring automatically call my UserSevice for check authorization. But how to specify HttpSecurity for save information about the session?
In Angular side I use HttpClient:
#Injectable()
export class CoreApi {
private baseUrl = 'http://localhost:8080/rest/';
constructor(public http: HttpClient) {
}
public get(url: string = ''): Observable<any> {
return this.http.get(this.getUrl(url));
}
}
Maybe You know how to specify Spring Security for checking auth with LoggedInChecker or another way for this reslt, let me know. Thank You!

Related

combining mutiple security configurations

I am currently working on a spring boot project that has multiple security (authentication) configurations combined:
a rest api with http basic auth
a rest api with jwt auth.
a web (form login) with 2fa auth.
The problem I am experiencing is, that the configurations cannot be entirely seperated. More specific: The authenticiation providers are accumulated (in the provider manager), which prevents my preferred setup from working correctly.
What happens is this: In config (3) i have a custom 2fa authentication provider which checks if the credentials (both password and 2FA code!) are entered correctly. If the password is correct, but the 2fa code is not, it exits (catches) with a (authentication or bad credentials) exception. However, as it exits the 2fa authentication provider, it goes back to the provider manager. The latter has another (DAO) auth provider at hand, and checks the credentials again: but this time: only password! not the 2fa code!). As the password is ok, it authorized the request.
So for short: I am experiencing a problem where the first authentication provider does NOT authorize, but the second does (because that one does not take the 2fa code into account)!
I have been at this for days, and i cannot seem to get this right.
As an alternative i have now opted for a solution using a 2fa custom filter. But is not my preferred solution, as it gives me some frontend problems (i first have to authorize the username/password, and only after that i can check the 2fa code).
Is there a solution using my 2fa auth provider? I would sort of wish that the auth providers would not get accumulated, so that when the first auth. provider exits with bad credentials, the auth procedure ends with a 'bad credentials'.
My config class:
WebSecurityConfig.java
#EnableWebSecurity
#Configuration
#AllArgsConstructor
public class WebSecurityConfig_backup extends WebSecurityConfigurerAdapter {
private UserDetailsService userDetailsService;
private PasswordEncoder passwordEncoder;
private HttpBasicAuthenticationExceptionHandler authenticationExceptionHandler;
private JwtAuthenticationProvider jwtAuthenticationProvider;
private MfaAuthenticationDetailsSource mfaAuthenticationDetailsSource;
private MfaAuthenticationProvider2 mfaAuthenticationProvider;
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Configuration
#Order(1)
public class ApiV1WebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/api/v1/**")
.httpBasic()
.authenticationEntryPoint(authenticationExceptionHandler)
.and()
.csrf().disable()
.authorizeRequests(authorize -> {
authorize
.mvcMatchers(HttpMethod.GET,
"/api/v1/transaction/**").hasAnyRole("BANK", "ADMIN")
.mvcMatchers(HttpMethod.POST,
"/api/v1/transaction/**").hasAnyRole("BANK", "ADMIN");
//.anyRequest().denyAll();
})
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth .userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder);
}
}
#Configuration
#Order(2)
public class ApiV2WebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/api/v2/**")
.addFilter(bearerTokenAuthenticationFilter())
.addFilter(credentialsAuthenticationFilter())
.csrf().disable()
.authorizeRequests(authorize -> {
authorize
.mvcMatchers(HttpMethod.GET,
"/api/v2/transaction/**").hasAnyRole("BANK", "ADMIN")
.mvcMatchers(HttpMethod.POST,
"/api/v2/transaction/**").hasAnyRole("BANK", "ADMIN");
//.anyRequest().denyAll();
})
.authorizeRequests()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
private BearerTokenAuthenticationFilter bearerTokenAuthenticationFilter() throws Exception {
BearerTokenAuthenticationFilter filter = new BearerTokenAuthenticationFilter(authenticationManager());
filter.setAuthenticationFailureHandler(authenticationFailureHandler());
return filter;
}
private CredentialsAuthenticationFilter credentialsAuthenticationFilter() throws Exception {
CredentialsAuthenticationFilter filter = new CredentialsAuthenticationFilter(authenticationManager());
filter.setAuthenticationFailureHandler(authenticationFailureHandler());
return filter;
}
private AuthenticationFailureHandler authenticationFailureHandler() {
return (request, response, ex) -> {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType(MediaType.APPLICATION_JSON.toString());
response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
ResponseWriterUtil.writeErrorResponse(response, ex.getMessage());
};
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(jwtAuthenticationProvider)
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder);
}
}
#Configuration
#Order(3)
public class FormWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
//authorisation
http//.addFilterBefore(googleTfaFilter, SessionManagementFilter.class)
.authorizeRequests(authorize -> {
authorize
.mvcMatchers("/", "/login", "/logout", "/registrationPage", "/register").permitAll()
.mvcMatchers(HttpMethod.GET,
"/others1", "/others2").hasAnyRole("USER", "ADMIN")
.mvcMatchers(HttpMethod.POST,
"/others1", "/others2").hasAnyRole("USER", "ADMIN");
})
.formLogin()
.loginPage("/login").permitAll()
.usernameParameter("email")
.loginProcessingUrl("/authenticate")
.defaultSuccessUrl("/")
.failureUrl("/login?error")
.authenticationDetailsSource(mfaAuthenticationDetailsSource)
.and()
.logout()
.deleteCookies("JSESSIONID")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
.logoutSuccessUrl("/login?logout").permitAll()
.and()
.sessionManagement()
.sessionFixation().migrateSession()
.and()
.headers().frameOptions().sameOrigin()
.and()
.csrf();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/css/**", "/js/**", "/img/**", "/lib/**");
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(mfaAuthenticationProvider)
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder);
}
}
}
auth provider for config 2:
#Slf4j
#RequiredArgsConstructor
#Component
public class JwtAuthenticationProvider implements AuthenticationProvider {
private final UserDetailsService userDetailsService;
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(BearerTokenAuthenticationToken.class);
}
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
BearerTokenAuthenticationToken bearerToken = (BearerTokenAuthenticationToken) authentication;
Authentication auth = null;
try {
//validate the token
Jwts.parser().setSigningKey(JWT_TOKEN_SECRET).parseClaimsJws(bearerToken.getToken());
JwtTokenUtil jwtTokenUtil = new JwtTokenUtil(bearerToken.getToken());
String username = jwtTokenUtil.getUsernameFromToken();
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
log.debug("Authentication token: " + auth);
} catch (IllegalArgumentException e) {
throw new UserServiceAuthenticationException("Invalid token");
} catch (ExpiredJwtException e) {
throw new UserServiceAuthenticationException("Token expired");
} catch (SignatureException e) {
throw new UserServiceAuthenticationException("Invalid signature");
}
return auth;
}
}
Auth provider for config (3)
#Slf4j
#AllArgsConstructor
#Component
public class MfaAuthenticationProvider2 implements AuthenticationProvider {
private UserRepo userRepository;
private GoogleAuthenticator googleAuthenticator;
private PasswordEncoder passwordEncoder;
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = authentication.getCredentials().toString();
String verficationCode = ((MfaAuthenticationDetails) authentication.getDetails()).getUserMFaCode();
User user = userRepository.findByEmail(authentication.getName()).stream().findFirst().orElse(null);
if(user == null || !passwordEncoder.matches(password, user.getPassword())){
throw new BadCredentialsException("Invalid username or password");
}
try {
if(!googleAuthenticator.authorizeUser(user.getUsername(), Integer.parseInt(verficationCode))){
throw new BadCredentialsException("Invalid verification code.");
}
} catch (Exception e) {
throw new BadCredentialsException("Authentication failed. Please try again.");
}
return new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
My current alternative solution for config 3:
#Slf4j
#Component
public class GoogleTfaFilter2 extends OncePerRequestFilter {
private final AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
private final GoogleTfaFailureHandler googleTfaFailureHandler = new GoogleTfaFailureHandler();
private final RequestMatcher urlIs2fa = new AntPathRequestMatcher("/verify2fa");
private final RequestMatcher urlIs2fa2 = new AntPathRequestMatcher("/register2fa");
private final RequestMatcher urlResource = new AntPathRequestMatcher("/resources/**");
private final RequestMatcher api = new AntPathRequestMatcher("/api/**");
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
StaticResourceRequest.StaticResourceRequestMatcher staticResourceRequestMatcher =
PathRequest.toStaticResources().atCommonLocations();
if (urlIs2fa.matches(request) || urlResource.matches(request) || urlIs2fa2.matches(request)||
staticResourceRequestMatcher.matcher(request).isMatch() || api.matches(request)) {
filterChain.doFilter(request, response);
return;
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && !authenticationTrustResolver.isAnonymous(authentication)){
log.debug("Processing 2FA Filter");
if (authentication.getPrincipal() != null && authentication.getPrincipal() instanceof User) {
User user = (User) authentication.getPrincipal();
if (!user.getMfaPassed()) {
log.debug("2FA Required");
request.getRequestDispatcher("/verify2fa").forward(request, response);
return;
}
}
}
filterChain.doFilter(request, response);
}
}

How to implement basic auth with spring boot?

I'm trying to add basic authentication to my spring boot back end. What I have so far is an angular front end login page and some basic authentication set up. Right now it allows one user account with user:"user" and password:"password". I'd like to be able to have database to store user details in and everytime someone trys to login the backend can just look for those details in the database. My plan is to use DynamoDB how would I do this from the websecurityconfig class?
Backend
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login")
.permitAll().anyRequest()
.authenticated()
.and()
.httpBasic();
}
}
Controller
public class LoginController {
#RequestMapping(value ="/login", method = RequestMethod.POST, headers = { "Content-type=application/json",
"Access-Control-Allow-Origin=*" }, consumes = "application/json")
public boolean login(#RequestBody UserModel user) {
System.out.println(user.getUsername());
System.out.println(user.getPassword());
return user.getUsername().equals("user") && user.getPassword().equals("password");
}
#RequestMapping("/user")
public Principal user(HttpServletRequest request) {
String authToken = request.getHeader("Authorization")
.substring("Basic".length()).trim();
return () -> new String(Base64.getDecoder()
.decode(authToken)).split(":")[0];
}
}

Spring security cannot logout

I've my custom implementation of Spring security in a Spring boot application. So I have my dependencies and I've a class named SecurityImpl which implements for me the login access.
When I get on the browser I'm correctly asked to login with an alert. When I login I have access to all of the #RequestMapping of my Spring Controller correctly. But I remain always logged. Even if I delete the JSESSIONID from my browser, when I make another http request, I am allowed and a new JSESSIONID is created and sent to my browser.
One weird thing is that even when I access with the login for the first time, even when the cookie is authomatically generated, the expiration date is: 1969-12-31T23:59:59.000Z
I've tried to invalidate the session, to delete the cookies from the server, to logout in various ways but nothing. Once logged, I am always allowed.
Here my SecurityImpl.java class which configurates my Spring Security:
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
#Configuration
#Component
public class SecurityImpl extends WebSecurityConfigurerAdapter implements AuthenticationProvider {
public static final String ROLE_ADMIN = "ROLE_ADMIN";
public static final String ROLE_USER = "ROLE_USER";
#Autowired UtenteDao utenteDao;
/* authentication provider part */
#Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
String username = auth.getName();
String password = auth.getCredentials().toString();
String ruolo = "";
Optional<Utente> utenteOptional = utenteDao.findByCodiceFiscaleAndPassword(username, password);
if(utenteOptional.isPresent()){
ruolo = utenteOptional.get().getRuolo();
}
if(ROLE_ADMIN.equals(ruolo)) {
List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority(ROLE_USER));
grantedAuths.add(new SimpleGrantedAuthority(ROLE_ADMIN));
return new UsernamePasswordAuthenticationToken(username, password, grantedAuths);
} else if(ROLE_USER.equals(ruolo)){
List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority(ROLE_USER));
return new UsernamePasswordAuthenticationToken(username, password, grantedAuths);
} else {
throw new BadCredentialsException("Autenticazione fallita");
}
}
#Override
public boolean supports(Class<?> auth) {
return auth.equals(UsernamePasswordAuthenticationToken.class);
}
/* websecurity adapter part: erase it if you don't want login alert but default spring login web page */
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(this); //this because it is either a WebSecurityAdapter than an AuthenticationProvider
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic()
.and()
.logout().clearAuthentication(true).logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/test")
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true);
}
/* per non filtrare con il login alcuni path */
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/test");
}
}
It doesn't work: when I go to /logout I'm redirected to /test correctly but when I ask for a forbidden path I'm allowed without any login.
Then I tried some solution in my #RestController:
#RequestMapping("/logout")
public String logoutPage (UsernamePasswordAuthenticationToken token) {
token.eraseCredentials();
token.setAuthenticated(false);
SecurityContextHolder.getContext().setAuthentication(null);
return "<h1>Logout effettuato con successo.</h1>";
}
then I tried:
#RequestMapping(value = "/logout")
public String loadApp(HttpServletRequest request) {
HttpSession session= request.getSession(false);
SecurityContextHolder.clearContext();
if(session != null) {
session.invalidate();
}
return "<h1>Logout effettuato con successo.</h1>";
}
Then, as a desperate, I tried:
#RequestMapping("/logout")
public String logoutDo(HttpServletRequest request){
HttpSession session= request.getSession(false);
SecurityContextHolder.clearContext();
session= request.getSession(false);
if(session != null) {
session.invalidate();
}
for(Cookie cookie : request.getCookies()) {
cookie.setMaxAge(0);
}
return "<h1>Logout effettuato con successo.</h1>";
}
I tried to use these methods and contemporarily delete my cookie from the browser. I've also tried to preauthorize forbidden method with the annotation #PreAuthorize, in the case they would be allowed (when you open a new browser, before first login, they are NOT allowed even without #PreAuthorize, but when login is made, IS FOREVER!)
The problem was the absence of the usage of showForm(). Without it, yes I insert my credentials within a Javascript alert which is presented to me. But no logout is possible.
So the code changes this way:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic()
.and()
.logout().clearAuthentication(true).logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/test")
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true);
}

How can I open main page if user is logined and tried open login page?(Spring security)

I use spring security in my project and I use custom authonticate. I save user from code.
#Override
public void saveUser(AuthLkUser lkUser) {
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
grantedAuths.add(grantedAuthority);
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(lkUser.getMsisdn(), lkUser.getPricePlan(), grantedAuths);
SecurityContextHolder.getContext().setAuthentication(result);
}
It work normaly. But after succsessufull login, I can open login page again.
I need disable possibility open login page after succsessufull login. I tried this:
.antMatchers("/login", "/default/login").access("hasRole('ANONYMOUS')")
But user with "USER" role can open login page too.
I tried
#Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException, ServletException {
// initialization logic after login
// redirect
HttpSession session = request.getSession();
SavedRequest savedReq = (SavedRequest) session.getAttribute("SAVED_REQUEST");
if (savedReq == null) {
response.sendRedirect(request.getContextPath() + "/landing");
}
else {
response.sendRedirect(savedReq.getRedirectUrl());
}
}
}
and setup to config
#Autowired
private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
.successHandler(myAuthenticationSuccessHandler)
But after succsessufull login this method not called.
How can I open main page if user is logined and tried open login page?
and why my myAuthenticationSuccessHandler not called?
it is my config
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/index").access("hasRole('USER')")
// .antMatchers("/login", "/default/login").access("hasRole('ANONYMOUS')")
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/j_spring_security_check")
.successHandler(myAuthenticationSuccessHandler)
.permitAll();
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/resources/**", "/**").permitAll()
.anyRequest().permitAll()
.and();
}
}
I think you need to add a controller in which you need to check for login request whether User is already logged in or not. If not logged in than display login page else redirect to home page. Following is such sample controller:
#Controller
#RequestMapping("/")
public class IndexController {
#RequestMapping(value="/login",method = RequestMethod.GET)
public String index(){
if(SecurityUtils.isUserLoggedIn())
return "redirect:/home";
return "login";
}
}
And following is sample SecurityUtils.java class which is utility class having method to check whether user is logged in or not :
public class SecurityUtils {
public static boolean isUserLoggedIn(){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(null != authentication){
return (authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken));
}else{
return false;
}
}
}

Not being able to provide custom authentication provider for the spring security

I want to have a custom Authentication Provider for spring security and i have implemented it like this
#Component
public class ApiCustomAuthenticationProvider implements AuthenticationProvider {
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
System.out.println("ahsgdvjasdhgjasjdh");
return new UsernamePasswordAuthenticationToken("aman", "12345");
}
#Override
public boolean supports(Class<?> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
}
Right now i don't have any logic as i just want to see if spring security is actually using this authentication provider .
i have my security config file as
#Configuration
#EnableWebSecurity
//#ImportResource("classpath:/security/spring_saml_sso_security.xml")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/*#Autowired
MetadataGeneratorFilter metadataGeneratorFilter;
#Autowired
FilterChainProxy samlFilter;
#Autowired
SAMLEntryPoint samlEntryPoint;
*/
#Autowired
private CustomUserDetailsService customUserDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
try {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/static/**").permitAll()
.antMatchers("/settings/api/**").permitAll()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.loginProcessingUrl("/login")
// .usernameParameter("username").passwordParameter("password")
.defaultSuccessUrl("/index",true)
.and()
.httpBasic();
// .defaultSuccessUrl("/", true);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("sadhiasdniaaaaaaaaaaaaaaaa:");
e.printStackTrace();
}
}
#Bean
public ApiCustomAuthenticationProvider apiCustomAuthenticationProvider() {
return new ApiCustomAuthenticationProvider();
}
}
i want to know if this
#Bean
public ApiCustomAuthenticationProvider apiCustomAuthenticationProvider() {
return new ApiCustomAuthenticationProvider();
is the correct way of telling spring security to use the custom authentication manager .
You need to add this in Spring security config:
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(new ApiCustomAuthenticationProvider());
}
or
auth.authenticationProvider(apiCustomAuthenticationProvider())
And as a reminder, if you return token :
UsernamePasswordAuthenticationToken("aman", "12345"),
spring will not give authorization to user. Instead you need to assign role :
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
UsernamePasswordAuthenticationToken("aman", "12345",grantedAuths) ;
As stated above,you are giving user ROLE_USER and then user can use all authenticated page.
Hope its help.

Categories