Я создал веб-приложение с Spring, в котором есть веб-интерфейс и API для поддержки соответствующего Android-приложения.Моя конфигурация безопасности:
@Configuration
@EnableWebSecurity
public class MultipleHttpSecurityConfig {
@Autowired
@Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authenticationProvider());
}
@Bean
public PlaintextPasswordEncoder passwordEncoder() {
return new PlaintextPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Bean
public AuthenticationTrustResolver getAuthenticationTrustResolver() {
return new AuthenticationTrustResolverImpl();
}
@Configuration
@Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
private static String REALM = "MY_TEST_REALM";
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().antMatcher("/api/**").authorizeRequests().antMatchers("/api/admin/**").hasRole("ADMIN").antMatchers("/api/**")
.access("hasRole('ADMIN') or hasRole('SUPERADMIN') or hasRole('TECHNICIAN') or hasRole('JUNIOR')").and().httpBasic().realmName(REALM)
.authenticationEntryPoint(getBasicAuthEntryPoint()).and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Bean
public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint() {
return new CustomBasicAuthenticationEntryPoint();
}
}
@Configuration
@Order(2)
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
PersistentTokenRepository tokenRepository;
@Autowired
@Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**").antMatchers("/static/**");
}
@Bean
public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices() {
PersistentTokenBasedRememberMeServices tokenBasedservice = new PersistentTokenBasedRememberMeServices("remember-me", userDetailsService, tokenRepository);
return tokenBasedservice;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
http.addFilterBefore(filter, CsrfFilter.class);
http.authorizeRequests().antMatchers("/signup", "/about", "/upload/**").permitAll().anyRequest()
.access("hasRole('ADMIN') or hasRole('SUPERADMIN') or hasRole('JUNIOR') or hasRole('TECHNICIAN')").and().formLogin().loginPage("/login").permitAll();
}
}
}
И у меня также есть отдельный контроллер для поддержки вызовов API, который предназначен для Android, и вот мой контроллер API:
@Controller
@RequestMapping("api")
public class ApiController {
@RequestMapping(value = { "/login/endpoint" }, method = RequestMethod.POST, produces = { "application/json" })
public ResponseEntity<MessageApi> apiPage(Authentication authentication) {
System.out.println(authentication.toString());
String[] userDetails = retrieveUsername();
User tempuser = userService.findUsersByUsername(userDetails[1]);
BigInteger bi = new BigInteger("0");
String userProfile = "";
String lastName = "";
String firstName = "";
if (tempuser != null) {
bi = tempuser.getUser_id();
Set<UserProfile> tUPs = tempuser.getUserProfiles();
for (UserProfile up : tUPs) {
userProfile = up.getType();
}
lastName = tempuser.getLastName();
firstName = tempuser.getFirstName();
}
return new ResponseEntity<MessageApi>(new MessageApi("OK", bi.toString(), userProfile, firstName, lastName), HttpStatus.OK);
}
"API"/ endpoint / login "- для проверки учетных данных и входа в систему из приложения Android.Моя проблема в том, что большую часть времени проверка API из приложения для Android "401 Unauthorized".Несколько раз в порядке.