-1

I want add a guest user with Ajax request :

$.ajax({
                    type : "GET",
                    url : restUrlUser + "/front/saveGuestUser",
                    success : function(res) {
                        if (res)
                            return res.id
                    }
                });

and in the controller i get the request with this method :

@RequestMapping("/front/saveGuestUser")
@ResponseBody
public Long saveGuestUser() {
    return iUserService.saveGuestUser();
}

and the in service layer i use the SecurityContextHolder and add the user into it :

@Transactional
    @Override
    public User saveGuestUser(){
        User entity=new User();
        Long userId=iUserRepository.getNextAutoIncrement();
        entity.setId(userId);
        entity.setUserName("guestUser"+userId.toString());
        entity.setFirstName("guestUser"+userId.toString());
        entity.setLastName("guestUser"+userId.toString());
        entity.setPassWord("password"+userId.toString());
        Set<GrantedAuthority> grant = new HashSet<GrantedAuthority>();
        grant.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        super.save(entity);
        entity.setAuthorities(grant);
        Authentication authentication =  new UsernamePasswordAuthenticationToken(entity, null, entity.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return entity;
    }

but when the request returns to the User Interface and i want to use application in another tab i get the 403 access denied . what should i have to do ?

Mohammad Mirzaeyan
  • 845
  • 3
  • 11
  • 30

1 Answers1

0

Make sure you're actually authenticating with the UsernamePasswordAuthenticationToken:

 Authentication token =  new UsernamePasswordAuthenticationToken(entity, null, entity.getAuthorities());
 Authentication authentication = this.authenticationProvider.authenticate(token);

See this related question for more detail: How to manually set an authenticated user in Spring Security / SpringMVC


Edit 1: If you're using Spring Security, you presumably have a WebSecurityConfigurerAdapter subclass already. You can wire in the AuthenticationProvider with something like this:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   @Bean
   public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
   }
}

In your service layer, you can then autowire the bean, like this:

public class WhateverService {

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    ....
}
Community
  • 1
  • 1
petesavitsky
  • 296
  • 3
  • 18