Skip to content

Instantly share code, notes, and snippets.

@asvignesh
Created August 13, 2019 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asvignesh/5c0ba9ed9e3db611717c0fba214ccb50 to your computer and use it in GitHub Desktop.
Save asvignesh/5c0ba9ed9e3db611717c0fba214ccb50 to your computer and use it in GitHub Desktop.
Spring boot REST Security
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
/**
* Created by asvignesh on 8/13/2019
*/
public class CustomAuthentication implements AuthenticationProvider {
Map<String, String> usernamePasswordMap;
public CustomAuthentication() {
this.usernamePasswordMap = new HashMap<>();
this.usernamePasswordMap.put("vignesh", "password");
this.usernamePasswordMap.put("vignesh2", "password2");
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String user = authentication.getName();
String password = authentication.getCredentials().toString();
if (!usernamePasswordMap.containsKey(user)) {
throw new BadCredentialsException("User doesn't exist");
}
String passwordStored = usernamePasswordMap.get(user);
if (passwordStored.equals(password)) {
return new UsernamePasswordAuthenticationToken(user, password, Collections.emptyList());
} else {
throw new BadCredentialsException("External system authentication failed");
}
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* Created by asvignesh on 8/13/2019
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
AuthenticationProvider provider = new CustomAuthentication();
auth.authenticationProvider(provider);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment