Spring security authorization without a password

Viewed 32

I'm making a rest app that has a single game token authorization that takes the required information about the user and authorizes it without a password, but I can't implement it, because when I try to do it, it says Bad Credentials (because I typed the wrong password, but it is not actually there in the authorization)

AuthController

@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) throws IOException {
    JSONObject jsonObject = readJsonFromUrl("https://api.vimeworld.com/misc/token/" + loginRequest.getToken());
    System.out.println(loginRequest.getToken());
    if (!jsonObject.getBoolean("valid")) {
        return ResponseEntity.badRequest().body(new MessageResponse("Error: Token is bad!"));
    }

    JSONObject owner = jsonObject.getJSONObject("owner");
    Long id = owner.getLong("id");
    String username = owner.getString("username");

    User user = new User(username, id);

    Set<String> strRoles = loginRequest.getRole();
    Set<Role> roles = new HashSet<>();
    if (strRoles == null) {
        Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
        roles.add(userRole);
    } else {
        strRoles.forEach(role -> {
            switch (role) {
                case "admin":
                    Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(adminRole);
                    break;
                case "mod":
                    Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(modRole);
                    break;
                default:
                    Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(userRole);
            }
        });
    }
    user.setRoles(roles);
    userRepository.save(user);


    Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(username, null));
    SecurityContextHolder.getContext().setAuthentication(authentication);
    String jwt = jwtUtils.generateJwtToken(authentication);
    System.out.println("goind");
    UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
    List<String> rolesUser = userDetails.getAuthorities().stream()
            .map(item -> item.getAuthority())
            .collect(Collectors.toList());
    return ResponseEntity.ok(new JwtResponse(jwt,
            userDetails.getId(),
            userDetails.getUsername(),
            rolesUser));
}

TokenAuthenticationFilter

public class TokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
@Autowired
private JwtUtils jwtUtils;
@Autowired
private UserDetailsServiceImpl userDetailsService;
private static final Logger logger = LoggerFactory.getLogger(TokenAuthenticationFilter.class);

private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher(
        "api/auth/signin", "POST");


public TokenAuthenticationFilter() {
    super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
}

public TokenAuthenticationFilter(AuthenticationManager authenticationManager) {
    super(DEFAULT_ANT_PATH_REQUEST_MATCHER, authenticationManager);
}


private String parseJwt(HttpServletRequest request) {
    String headerAuth = request.getHeader("Authorization");
    if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
        return headerAuth.substring(7, headerAuth.length());
    }
    return null;
}

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    try {
        String jwt = parseJwt(request);
        if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
            String username = jwtUtils.getUserNameFromJwtToken(jwt);
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return authentication;
        }
    } catch (Exception e) {
        logger.error("Cannot set user authentication: {}", e);
    }
    return null;
}

}

WebSecurityConfig

@Configuration
@EnableWebSecurity
 @EnableGlobalMethodSecurity(
    prePostEnabled = true)
  public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsServiceImpl userDetailsService;
@Autowired
private AuthEntryPointJwt unauthorizedHandler;
@Bean
public TokenAuthenticationFilter tokenAuthenticationFilter() throws Exception {
    TokenAuthenticationFilter authenticationFilter = new TokenAuthenticationFilter();
    authenticationFilter.setAuthenticationManager(authenticationManagerBean());
    authenticationFilter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/login?error"));

    return authenticationFilter;
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests().antMatchers("/api/auth/**").permitAll()
            .antMatchers("/api/test/**").permitAll()
            .anyRequest().authenticated();
        http.addFilterAt(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}

}

0 Answers
Related