[英]How do you configure spring security to authenticate against a database using basic auth?
[英]Authenticate a Springboot Application against another application using Basic Auth
如何針對第三方應用程序認證Spring Boot應用程序?
根據使用spring安全性實現基本身份驗證的示例,驗證了用戶名和密碼,但是我想針對另一個服務的200條響應進行驗證。 驗證用戶身份的方法如下:用戶使用基本身份驗證發送憑據以訪問我的SpringBoot REST服務-> SpringBoot服務通過基本身份驗證標頭向第三方服務發出GET請求->收到200 OK並驗證最終用戶訪問我的REST服務上的所有URL。
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationEntryPoint authEntryPoint;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.anyRequest().authenticated()
.and().httpBasic()
.authenticationEntryPoint(authEntryPoint);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
}
您必須實現自己的AuthenticationProvider
。 例如:
public class ThirdPartyAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication auth) thows AuthenticationException {
// call third party site with auth.getPrincipal() and auth.getCredentials() (those are username and password)
// Throw AuthenticationException if response is not 200
return new UsernamePasswordAuthenticationToken(...);
}
@Override
public boolen supports(Class<?> authCls) {
return UsernamePasswordAuthenticationToken.class.equals(authCls);
}
}
之后,您可以在SpringSecurityConfig
重寫configure(AuthenticationManagerBuilder)
方法:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// authProvider = instance of ThirdPartyAuthenticationProvider
auth.authenticationProvider(authProvider);
}
我使用UserDetailsService使它工作。 我創建了一個休息模板,並調用了我的第三方服務來對用戶進行身份驗證,並且在收到響應后,用戶可以訪問所有請求。 這是我的方法:
SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationEntryPoint authEntryPoint;
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic()
.authenticationEntryPoint(authEntryPoint);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth, UserDetailsService userDetailsService)
throws Exception {
auth.userDetailsService(userDetailsService);
}
ABCUserDetails.java
@Service("userDetailsService")
public class ABCUserDetails implements UserDetailsService {
@Autowired
private UserService userService;
@Override
public UserDetails loadUserByUsername(String abcuser) throws UsernameNotFoundException {
// TODO Auto-generated method stub
Map<String, Object> userMap = userService.getUserByUsername(abcuser);
// check if this user with this username exists, if not, throw an
// exception
// and stop the login process
if (userMap == null) {
throw new UsernameNotFoundException("User details not found : " + abcuser);
}
String username = (String) userMap.get("username");
String password = (String) userMap.get("password");
String role = (String) userMap.get("role");
List<SimpleGrantedAuthority> authList = getAuthorities(role);
User user = new User(username, password, authList);
return user;
}
private List<SimpleGrantedAuthority> getAuthorities(String role) {
List<SimpleGrantedAuthority> authList = new ArrayList<>();
authList.add(new SimpleGrantedAuthority("ROLE_USER"));
if (role != null && role.trim().length() > 0) {
if (role.equals("myrole")) {
authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
}
return authList;
}
}
UserService.java
@Service("userService")
public class UserService {
public Map<String, Object> getUserByUsername(String username) {
// TODO Auto-generated method stub
Map<String, Object> userMap = null;
//get current request attributes
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
String authToken = attr.getRequest().getHeader("Authorization");
final String encodedUserPassword = authToken.replaceFirst("Basic" + " ", "");
String usernameAndPassword = null;
try {
byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
usernameAndPassword = new String(decodedBytes, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
final String username1 = tokenizer.nextToken();
final String password = tokenizer.nextToken();
//thirdparty url
final String uri = "http://abcurlauthprovider/userid="
+ "\"" + username1 + "\"";
RestTemplate restTemplate = new RestTemplate();
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic " + encodedUserPassword);
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> mresponse = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
if (username.equals(username1) || username.equals(username1)) {
userMap = new HashMap<>();
userMap.put("username", username1);
userMap.put("password", password);
userMap.put("role", (username.equals(username1)) ? username1 : username1);
// return the usermap
return userMap;
}
} catch (Exception eek) {
System.out.println("** Exception: " + eek.getMessage());
}
return null;
}
}
這是我的AuthenticatioEntryPoint.java
@Component
public class AuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
throws IOException, ServletException {
response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 - " + authEx.getMessage());
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("----------------------inside afterPropertiesSet method");
setRealmName("MYAPI");
super.afterPropertiesSet();
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.