Tag: spring security

在Spring Security Java Config中创建多个HTTP部分

使用Spring Security XML配置,您可以定义多个HTTP元素,以便为应用程序的不同部分指定不同的访问规则。 8.6高级命名空间配置中给出的示例定义了应用程序的单独的有状态和无状态部分,前者使用会话和表单登录,后者不使用会话和BASIC身份validation: 我无法弄清楚如何使用Java Config做同样的事情。 重要的是我禁用会话并为我的Web服务使用不同的入口点。 现在我有以下内容: @Override public void configure(WebSecurity security) { security.ignoring().antMatchers(“/resource/**”, “/favicon.ico”); } @Override protected void configure(HttpSecurity security) throws Exception { security .authorizeRequests() .anyRequest().authenticated() .and().formLogin() .loginPage(“/login”).failureUrl(“/login?loginFailed”) .defaultSuccessUrl(“/ticket/list”) .usernameParameter(“username”) .passwordParameter(“password”) .permitAll() .and().logout() .logoutUrl(“/logout”).logoutSuccessUrl(“/login?loggedOut”) .invalidateHttpSession(true).deleteCookies(“JSESSIONID”) .permitAll() .and().sessionManagement() .sessionFixation().changeSessionId() .maximumSessions(1).maxSessionsPreventsLogin(true) .sessionRegistry(this.sessionRegistryImpl()) .and().and().csrf() .requireCsrfProtectionMatcher((r) -> { String m = r.getMethod(); return !r.getServletPath().startsWith(“/services/”) && (“POST”.equals(m) || […]

使用java配置在单个应用程序中的多个身份validation机制

目前我的应用程序中有一个身份validation机制,即使用LDAP进行身份validation和授权。 我的安全配置如下所示 @Configuration @EnableWebMvcSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .anyRequest().fullyAuthenticated() .and() .httpBasic(); } @Configuration protected static class AuthenticationConfiguration extends GlobalAuthenticationConfigurerAdapter { @Value(“${ldap-${env}.manager.dn}”) private String managerDn; @Value(“${ldap-${env}.manager.pass}”) private String managerPass; @Value(“${ldap-${env}.server.url}”) private String url; @Value(“${ldap.password.attribute:userPassword}”) private String passwordAttr; @Override public void init(AuthenticationManagerBuilder auth) throws […]

如何在Spring Security中使用自定义角色/权限?

在将旧应用程序迁移到spring安全性时,我遇到以下exception: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘_filterChainProxy’: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘_filterChainList’: Cannot resolve reference to bean ‘_filterSecurityInterceptor’ while setting bean property ‘filters’ with key [3]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘_filterSecurityInterceptor’: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: […]

如何解决Spring Security中的角色?

我正在尝试在我的项目中使用Spring Security,这里是代码: @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // TODO Auto-generated method stub //super.configure(auth); //auth.inMemoryAuthentication().withUser(“admin”).password(“1111”).roles(“USER”); auth .jdbcAuthentication() .dataSource(dataSource) .usersByUsernameQuery(“select username, password, 1 from users where username=?”) .authoritiesByUsernameQuery(“select users_username, roles_id from roles_users where users_username=?”) .rolePrefix(“ROLE_”); } @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable(); http .httpBasic(); http .authorizeRequests() .anyRequest().authenticated(); http .authorizeRequests() .antMatchers(“/users/all”).hasRole(“admin”) […]

Spring Security的跨源资源共享

我正在努力让CORS与Spring Security很好地合作,但它并不符合。 我做了本文中描述的更改并在applicationContext-security.xml更改此行已经为我的应用程序提供了POST和GET请求(暂时公开控制器方法,因此我可以测试CORS): 之前: 之后: 不幸的是,以下允许通过AJAX进行Spring Security登录的URL没有响应: http://localhost:8080/mutopia-server/resources/j_spring_security_check 。 我正在从http://localhost:80到http://localhost:8080发出AJAX请求。 在Chrome中 在尝试访问j_spring_security_check我在Chrome中获取(pending) OPTIONS预检请求,并且AJAX调用返回HTTP状态代码0和消息“错误”。 在Firefox中 预检成功使用HTTP状态代码302,然后我仍然直接获得我的AJAX请求的错误回调,其中HTTP状态为0,消息为“error”。 AJAX请求代码 function get(url, json) { var args = { type: ‘GET’, url: url, // async: false, // crossDomain: true, xhrFields: { withCredentials: false }, success: function(response) { console.debug(url, response); }, error: function(xhr) { console.error(url, xhr.status, xhr.statusText); } }; if (json) […]

Spring Security 5:没有为id“null”映射PasswordEncoder

我正在从Spring Boot 1.4.9迁移到Spring Boot 2.0以及Spring Security 5,我正在尝试通过OAuth 2进行身份validation。但是我收到此错误: java.lang.IllegalArgumentException:没有为id“null”映射PasswordEncoder 从Spring Security 5的文档中,我了解到密码的存储格式已更改。 在我当前的代码中,我创建了我的密码编码器bean: @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } 但它给了我以下错误: 编码密码看起来不像BCrypt 所以我按照Spring Security 5文档更新编码器: @Bean public PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); } 现在,如果我能在数据库中看到密码,那么它就是存储的 {bcrypt}$2a$10$LoV/3z36G86x6Gn101aekuz3q9d7yfBp3jFn7dzNN/AL5630FyUQ 随着第一个错误消失,现在当我尝试进行身份validation时,我得到以下错误: java.lang.IllegalArgumentException:没有为id“null”映射PasswordEncoder 为了解决这个问题,我尝试了Stackoverflow的以下所有问题: Spring Boot PasswordEncoder错误 Spring Oauth2。 密码编码器未在DaoAuthenticationProvider中设置 这是一个类似于我的问题,但没有回答: Spring Security 5 – 密码迁移 注意:我已将加密密码存储在数据库中,因此无需再在UserDetailsService进行编码。 在Spring security […]

为什么使用基于java的配置的Spring应用程序无法正常工作

我最近开始使用Spring框架开发一个带有ojective的项目来开发它,没有XML配置文件,只有Java代码。 在当前时刻,我将以下文件添加到我的项目中: WebAppConfig.java @EnableWebMvc @ComponentScan(value=”org.webapp”) @Configuration public class WebAppConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(“/css/**”).addResourceLocations(“/css/”).setCachePeriod(31556926); registry.addResourceHandler(“/css/**”).addResourceLocations(“/fonts/”).setCachePeriod(31556926); registry.addResourceHandler(“/img/**”).addResourceLocations(“/image/”).setCachePeriod(31556926); registry.addResourceHandler(“/js/**”).addResourceLocations(“/js/”).setCachePeriod(31556926); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Bean public InternalResourceViewResolver getInternalResourceViewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix(“/WEB-INF/jsp/”); resolver.setSuffix(“.jsp”); return resolver; } } SecurityConfig.java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter […]

具有Spring Security和Java配置的自定义validation管理器

我正在使用Spring Security与SpringMVC创建一个Web应用程序(为了清楚起见,我将其称为WebApp),它与现有应用程序相对应(我将其称为BackendApp)。 我想将身份validation职责委派给BackendApp(这样我就不需要同步这两个应用程序)。 为了实现这一点,我希望WebApp(运行Spring安全性)通过REST与用户在表单中提供的用户名和密码与BackendApp进行通信,并根据BackendApp的响应是200 OK还是401 Unauthorized进行身份validation。 我知道我需要编写一个自定义的身份validation管理器来执行此操作,但我是一个非常新的spring,无法找到有关如何实现它的任何信息。 我相信我需要做这样的事情: public class CustomAuthenticationManager implements AuthenticationManager{ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String pw = authentication.getCredentials().toString(); // Code to make rest call here and check for OK or Unauthorised. // What do I return? } } 如果成功,我是否设置authentication.setAuthenticated(true),否则设置为false,那就是它? 编写完成后,如何使用java配置文件配置spring security以使用此身份validation管理器? 在此先感谢您的任何帮助。

Spring安全CORSfilter

我们在现有项目中添加了Spring Security 。 从这一刻起,我们得到一个401 No ‘Access-Control-Allow-Origin’ header is present on the requested resource我们服务器No ‘Access-Control-Allow-Origin’ header is present on the requested resource错误上。 那是因为没有Access-Control-Allow-Origin标头附加到响应。 为了解决这个问题,我们在注销过滤Filter之前添加了我们自己的filter,它在Filter链中,但filter不适用于我们的请求。 我们的错误: XMLHttpRequest无法加载http://localhost:8080/getKunden 。 请求的资源上不存在“Access-Control-Allow-Origin”标头。 原因http://localhost:3000因此不允许访问。 响应具有HTTP状态代码401。 我们的安全配置: @EnableWebSecurity @Configuration @ComponentScan(“com.company.praktikant”) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private MyFilter filter; @Override public void configure(HttpSecurity http) throws Exception { final UrlBasedCorsConfigurationSource source = […]

Spring Security登录页面

我开发了一个使用Spring Security默认登录页面的应用程序。 但是我想实现自己的登录页面。 我将放一个login.html而不是一个jsp页面。 我想用它来使用JQuery。 我检查了许多例子,但无法实现。 我是Spring和Spring Security的新手,我使用Spring Security 3.我应该遵循哪些步骤的想法?