Spring引导安全Ldap Rest控制器
我目前正在使用SpringSecurityLDAP实现RESTController 登录成功,用户信息返回良好 当angular中的前端想要调用我的RESTAPI时,问题就来了,安全性返回未经授权的状态。(不应该像我应该登录的那样) 我是spring security的新手,所以我的配置中可能缺少一些简单的东西:) 以下是一些截图和配置代码示例(出于保密目的,我从截图中删除了一些数据):Spring引导安全Ldap Rest控制器,spring,spring-security,spring-boot,spring-ldap,spring-restcontroller,Spring,Spring Security,Spring Boot,Spring Ldap,Spring Restcontroller,我目前正在使用SpringSecurityLDAP实现RESTController 登录成功,用户信息返回良好 当angular中的前端想要调用我的RESTAPI时,问题就来了,安全性返回未经授权的状态。(不应该像我应该登录的那样) 我是spring security的新手,所以我的配置中可能缺少一些简单的东西:) 以下是一些截图和配置代码示例(出于保密目的,我从截图中删除了一些数据): @配置 @启用Web安全性 @EnableGlobalMethodSecurity(securedEna
@配置
@启用Web安全性
@EnableGlobalMethodSecurity(securedEnabled=true)
@组件扫描(“com.*”)
@PropertySource(值={“classpath:application.properties”})
公共类LdapSecurityConfig扩展了websecurityconfig适配器{
@自动连线
私有HttpAuthenticationEntryPoint authenticationEntryPoint;
@自动连线
私有AuthSuccessHandler AuthSuccessHandler;
@自动连线
私有AuthFailureHandler AuthFailureHandler;
@自动连线
私有HttpLogoutSuccessHandler logoutSuccessHandler;
@豆子
@凌驾
公共AuthenticationManager authenticationManagerBean()引发异常{
返回super.authenticationManagerBean();
}
@豆子
@凌驾
公共UserDetailsService userDetailsServiceBean()引发异常{
返回super.userDetailsServiceBean();
}
@豆子
公共AuthenticationProvider AuthenticationProvider()引发异常{
LdapAuthenticationProvider LdapAuthenticationProvider=新的LdapAuthenticationProvider(getBindAuthenticator());
ldapAuthenticationProvider.setUserDetailsContextMapper(新的UserDetailsContextMapperImpl());
返回ldapAuthenticationProvider;
}
@凌驾
受保护的AuthenticationManager AuthenticationManager()引发异常{
返回super.authenticationManager();
}
@凌驾
受保护的无效配置(HttpSecurity http)引发异常{
http.authenticationProvider(authenticationProvider())
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
.及()
.csrf().disable()
.addFilterBefore(新的CORSFilter(),ChannelProcessingFilter.class)
.authorizeRequests().antMatchers(authorizeRequestsCurrentUser).permitAll()
.及()
.authorizeRequests().anyRequest().authorized()
.和().记住()
.及()
.formLogin()
.permitAll()
.loginProcessingUrl(loginProcessingUrl)
.usernameParameter(usernameParameter)
.passwordParameter(userPasswordParameter)
.successHandler(authSuccessHandler)
.failureHandler(authFailureHandler)
.及()
.logout().permitAll()
.deleteCookies(“JSSessionID”)
.logoutRequestMatcher(新的AntPathRequestMatcher(logoutRequestMatcher,RequestMethod.GET.name()))
.logoutSuccessHandler(logoutSuccessHandler)
.logoutSuccessUrl(logoutSuccessUrl)
.clearAuthentication(true)
.及()
.会议管理()
.最多会议(1);
}
@自动连线
public void configureGlobal(AuthenticationManagerBuilder auth)引发异常{
auth.eraseCredentials(false).authenticationProvider(authenticationProvider()).ldapaauthentication()
.userSearchFilter(ldapUserSearchFilter)
.groupSearchBase(ldapGroupSearchBase)
.userDetailsContextMapper(新的UserDetailsContextMapperImpl())
.contextSource(getLdapContextSource());
}
私有BindAuthenticator getBindAuthenticator()引发异常{
LdapContextSource contextSource=getLdapContextSource();
字符串searchFilter=ldapSearchfilter;
FilterBasedLdapUserSearch userSearch=新的FilterBasedLdapUserSearch(ldapSearchBase、searchFilter、contextSource);
userSearch.setSearchSubtree(true);
BindAuthenticator BindAuthenticator=新的BindAuthenticator(contextSource);
bindAuthenticator.setUserSearch(userSearch);
bindAuthenticator.afterPropertiesSet();
返回绑定验证器;
}
私有LdapContextSource getLdapContextSource()引发异常{
LdapContextSource cs=新的LdapContextSource();
cs.setUrl(ldapUrl);
cs.setBase(ldapBase);
cs.setUserDn(ldapUserDn);
cs.setPassword(ldapPassword);
cs.setPooled(真);
cs.afterPropertiesSet();
返回cs;
}
}
@组成部分
@Log4j
公共类AuthSuccessHandler扩展了SavedRequestStataWareAuthenticationSuccessHandler{
私有最终对象映射器映射器;
@自动连线
AuthSuccessHandler(映射Jackson2HttpMessageConverter messageConverter){
this.mapper=messageConverter.getObjectMapper();
}
@凌驾
AuthenticationSuccess(HttpServletRequest请求、HttpServletResponse响应、,
身份验证)引发IOException、ServletException{
LdapUser authUser=(LdapUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
MyUser=新的MyUser();
user.setUsername(authUser.getUsername());
user.setPassword(cred);
//将我们的响应设置为OK状态
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(MediaType.APPLICATION_JSON_VALUE+“charset=UTF-8”);
PrintWriter=response.getWriter();
writeValue(writer,authUser);
writer.flush();
}
}
公共类CORSFilter实现过滤器{
@凌驾
public void init(FilterConfig
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
@ComponentScan("com.*")
@PropertySource(value= {"classpath:application.properties"})
public class LdapSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private HttpAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private AuthSuccessHandler authSuccessHandler;
@Autowired
private AuthFailureHandler authFailureHandler;
@Autowired
private HttpLogoutSuccessHandler logoutSuccessHandler;
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
@Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
@Bean
public AuthenticationProvider authenticationProvider() throws Exception {
LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(getBindAuthenticator());
ldapAuthenticationProvider.setUserDetailsContextMapper(new UserDetailsContextMapperImpl());
return ldapAuthenticationProvider;
}
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authenticationProvider(authenticationProvider())
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
.and()
.csrf().disable()
.addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class)
.authorizeRequests().antMatchers(authorizeRequestsCurrentUser).permitAll()
.and()
.authorizeRequests().anyRequest().authenticated()
.and().rememberMe()
.and()
.formLogin()
.permitAll()
.loginProcessingUrl(loginProcessingUrl)
.usernameParameter(userNameParameter)
.passwordParameter(userPasswordParameter)
.successHandler(authSuccessHandler)
.failureHandler(authFailureHandler)
.and()
.logout().permitAll()
.deleteCookies("JSESSIONID")
.logoutRequestMatcher(new AntPathRequestMatcher(logoutRequestMatcher, RequestMethod.GET.name()))
.logoutSuccessHandler(logoutSuccessHandler)
.logoutSuccessUrl(logoutSuccessUrl)
.clearAuthentication(true)
.and()
.sessionManagement()
.maximumSessions(1);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.eraseCredentials(false).authenticationProvider(authenticationProvider()).ldapAuthentication()
.userSearchFilter(ldapUserSearchFilter)
.groupSearchBase(ldapGroupSearchBase)
.userDetailsContextMapper(new UserDetailsContextMapperImpl())
.contextSource(getLdapContextSource());
}
private BindAuthenticator getBindAuthenticator()throws Exception{
LdapContextSource contextSource = getLdapContextSource();
String searchFilter=ldapSearchfilter;
FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(ldapSearchBase, searchFilter,contextSource);
userSearch.setSearchSubtree(true);
BindAuthenticator bindAuthenticator = new BindAuthenticator(contextSource);
bindAuthenticator.setUserSearch(userSearch);
bindAuthenticator.afterPropertiesSet();
return bindAuthenticator;
}
private LdapContextSource getLdapContextSource() throws Exception {
LdapContextSource cs = new LdapContextSource();
cs.setUrl(ldapUrl);
cs.setBase(ldapBase);
cs.setUserDn(ldapUserDn);
cs.setPassword(ldapPassword);
cs.setPooled(true);
cs.afterPropertiesSet();
return cs;
}
}
@Component
@Log4j
public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
private final ObjectMapper mapper;
@Autowired
AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) {
this.mapper = messageConverter.getObjectMapper();
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
LdapUser authUser = (LdapUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
MyUser user = new MyUser();
user.setUsername(authUser.getUsername());
user.setPassword(cred);
// set our response to OK status
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(MediaType.APPLICATION_JSON_VALUE+"; charset=UTF-8");
PrintWriter writer = response.getWriter();
mapper.writeValue(writer, authUser);
writer.flush();
}
}
public class CORSFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true");
response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, OPTIONS, DELETE");
response.setHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600");
response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "x-requested-with");
chain.doFilter(request, response);
}
public void destroy() {}
}
@Component
public class UserDetailsContextMapperImpl extends LdapUserDetailsMapper {
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
Collection<? extends GrantedAuthority> authorities) {
UserDetails userDetails= super.mapUserFromContext(ctx,username,authorities);
String fullName = ctx.getStringAttribute("givenName");
String email = ctx.getStringAttribute("mail");
return new LdapUser((LdapUserDetails)userDetails,fullName,email);
}
}
@Log4j
@CrossOrigin
@RestController
@ComponentScan("com.*")
@RequestMapping(value = "${config.rest.uri.entry.path}", produces = MediaType.APPLICATION_JSON_VALUE)
public class DashboardController {
@Autowired
IDashboardService dashboardService;
@RequestMapping(value = "${config.rest.uri.dashboard.documents}",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
public Result<List<DashboardDocument>> getDocumentList(@RequestParam(value="username") String username){
----------------
return result;
}
}
SavedRequest savedRequest
= requestCache.getRequest(request, response);
if (savedRequest == null) {
clearAuthenticationAttributes(request);
return;
}
String targetUrlParam = getTargetUrlParameter();
if (isAlwaysUseDefaultTargetUrl()
|| (targetUrlParam != null
&& StringUtils.hasText(request.getParameter(targetUrlParam)))) {
requestCache.removeRequest(request, response);
clearAuthenticationAttributes(request);
return;
}
clearAuthenticationAttributes(request);