我是Spring Security的新手.如何添加将在用户成功登录时调用的事件侦听器?此外,我需要在此侦听器中获取某种唯一的会话ID,该ID应该可以进一步使用.我需要此ID与另一台服务器同步.
有很多指南,示例代码显示如何使用Spring Security保护REST API,但大多数都假设一个Web客户端并谈论登录页面,重定向,使用cookie等.甚至可能是一个简单的过滤器,检查HTTP标头中的自定义标记可能就足够了.如何实现以下要求的安全性?有没有任何gist/github项目做同样的事情?我对弹簧安全的了解有限,所以如果有更简单的方法来实现弹簧安全性,请告诉我.
我使用Springboot,spring security等.更喜欢使用Java配置的解决方案(没有XML)
rest restful-authentication spring-security stateless spring-boot
我试图了解如何使用OAuth2RestTemplate对象来使用我的OAuth2安全REST服务(在不同的项目下运行,让我们假设在不同的服务器等...)
我的休息服务是:
http://localhost:8082/app/helloworld
Run Code Online (Sandbox Code Playgroud)
- >访问此URL会生成错误,因为我未经过身份验证
要请求令牌,我会去:
http://localhost:8082/app/oauth/token?grant_type=password&client_id=restapp&client_secret=restapp&username=**USERNAME**&password=**PASSWORD**
Run Code Online (Sandbox Code Playgroud)
收到令牌后,我可以使用以下URL连接到REST API(插入示例令牌)
http://localhost:8082/app/helloworld/?access_token=**4855f557-c6ee-43b7-8617-c24591965206**
Run Code Online (Sandbox Code Playgroud)
现在我的问题是如何实现可以使用这个OAuth2安全REST API的第二个应用程序?我真的没有找到任何提供用户名和密码的工作示例(例如来自登录表单),然后生成一个令牌,可以重新使用该令牌从REST API获取数据.
我目前尝试使用以下对象:
BaseOAuth2ProtectedResourceDetails baseOAuth2ProtectedResourceDetails = new BaseOAuth2ProtectedResourceDetails();
baseOAuth2ProtectedResourceDetails.setClientId("restapp");
baseOAuth2ProtectedResourceDetails.setClientSecret("restapp");
baseOAuth2ProtectedResourceDetails.setGrantType("password");
// how to set user name and password ???
DefaultAccessTokenRequest accessTokenRequest = new DefaultAccessTokenRequest();
OAuth2ClientContext oAuth2ClientContext = new DefaultOAuth2ClientContext(accessTokenRequest());
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(baseOAuth2ProtectedResourceDetails,oAuth2ClientContext);
Run Code Online (Sandbox Code Playgroud)
但这只是不起作用:(
非常感谢任何想法或非常感谢链接到工作示例和教程.
我正在从Spring Boot 1.4.9迁移到Spring Boot 2.0以及Spring Security 5,我正在尝试通过OAuth 2进行身份验证.但是我收到此错误:
java.lang.IllegalArgumentException:没有为id"null"映射PasswordEncoder
从Spring Security 5的文档中,我了解到密码的存储格式已更改.
在我当前的代码中,我创建了我的密码编码器bean:
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
Run Code Online (Sandbox Code Playgroud)
但它给了我以下错误:
编码密码看起来不像BCrypt
所以我按照Spring Security 5文档更新编码器:
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
Run Code Online (Sandbox Code Playgroud)
现在如果我可以在数据库中看到密码,那么它就是存储的
{bcrypt}$2a$10$LoV/3z36G86x6Gn101aekuz3q9d7yfBp3jFn7dzNN/AL5630FyUQ
Run Code Online (Sandbox Code Playgroud)
随着第一个错误消失,现在当我尝试进行身份验证时,我收到以下错误:
java.lang.IllegalArgumentException:没有为id"null"映射PasswordEncoder
为了解决这个问题,我尝试了Stackoverflow的以下所有问题:
这是一个类似于我的问题,但没有回答:
注意:我已将加密密码存储在数据库中,因此无需再次编码UserDetailsService.
在Spring security 5文档中,他们建议您可以使用以下方法处理此异常:
DelegatingPasswordEncoder.setDefaultPasswordEncoderForMatches(的PasswordEncoder)
如果这是修复,那么我应该把它放在哪里?我试过把它放在PasswordEncoder像下面这样的bean中,但它没有用:
DelegatingPasswordEncoder def = new DelegatingPasswordEncoder(idForEncode, encoders);
def.setDefaultPasswordEncoderForMatches(passwordEncoder);
Run Code Online (Sandbox Code Playgroud)
MyWebSecurity类
@Configuration
@EnableWebSecurity
public class SecurityConfiguration …Run Code Online (Sandbox Code Playgroud) java spring spring-security spring-boot spring-security-oauth2
我正在使用Spring Security来保护Struts2 Web应用程序.由于项目限制,我使用的是Spring Security 2.06.
我的团队构建了一个自定义用户管理API,用于在接收用户名和密码参数后对用户进行身份验证,并返回包含角色列表和其他属性(如电子邮件,名称等)的自定义用户对象.
根据我的理解,典型的Spring Security用例使用默认的UserDetailsService来检索UserDetails对象; 此对象将包含(以及其他内容)框架将用于对用户进行身份验证的密码字段.
在我的情况下,我想让我们的自定义API执行身份验证,然后返回包含角色和其他属性(电子邮件等)的自定义UserDetails对象.
经过一些研究,我发现我可以通过AuthenticationProvider的自定义实现来实现这一点.我也有UserDetailsService和UserDetails的自定义实现.
我的问题是我真的不明白我应该在CustomAuthenticationProvider中返回什么.我在这里使用自定义UserDetailsService对象吗?甚至需要吗?对不起,我真的很困惑.
CustomAuthenticationProvider:
public class CustomAuthenticationProvider implements AuthenticationProvider {
private Logger logger = Logger.getLogger(CustomAuthenticationProvider.class);
private UserDetailsService userDetailsService; //what am i supposed to do with this?
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
String username = String.valueOf(auth.getPrincipal());
String password = String.valueOf(auth.getCredentials());
logger.info("username:" + username);
logger.info("password:" + password);
/* what should happen here? */
return null; //what do i return?
}
@Override
public boolean supports(Class aClass) …Run Code Online (Sandbox Code Playgroud) 我使用 Spring Boot 3.0,当我进行安全配置时,我收到一条警告,指出它@EnableGlobalMethodSecurity已被弃用。
@Configuration
@EnableWebSecurity
@AllArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
Run Code Online (Sandbox Code Playgroud)
@EnableGlobalMethodSecurity在 Spring boot 3.0 中我可以用什么来替代?
我有Eclipse Maven web项目,我使用Spring mvc和Spring安全性.当我试图启动它时,它并没有取决于初始化上下文:
Could not open ServletContext resource [/WEB-INF/spring-dispatcher-servlet.xml]
更多细节如下:
这是我的 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Web Manager</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/app-config.xml, /WEB-INF/spring/security-config.xml
</param-value>
</context-param>
<!-- Spring MVC -->
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Run Code Online (Sandbox Code Playgroud)
这是我的 app-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context" …Run Code Online (Sandbox Code Playgroud) web-applications spring-mvc spring-security maven-eclipse-plugin
我正在使用Spring 4开发一个REST API.我想使用Spring Security来保护一些端点,但根据我读过的内容,可以使用@EnableGlobalMethodSecurity或者@EnableWebSecurity.不幸的是,我为这些文档找到的文档并没有清楚地解释它们的作用(或它们如何比较).如果我想根据标准关系数据库中声明的数据和关系来保护Spring REST API的身份验证和授权,那么在Spring 4中实现这一目的的推荐方法是什么?
我在使用Spring Security && Thymeleaf时遇到问题,特别是在尝试使用hasRole表达式时.'admin'用户有一个'ADMIN'角色,但hasRole('ADMIN')无论如何我会尝试将其解析为false
我的HTML:
1.<div sec:authentication="name"></div> <!-- works fine -->
2.<div sec:authentication="principal.authorities"></div> <!-- works fine -->
3.<div sec:authorize="isAuthenticated()" >true</div> <!-- works fine -->
4.<span th:text="${#authorization.expression('isAuthenticated()')}"></span> <!-- works fine -->
5.<div th:text="${#vars.role_admin}"></div> <!--Works fine -->
6.<div sec:authorize="${hasRole('ADMIN')}" > IS ADMIN </div> <!-- Doesnt work -->
7.<div sec:authorize="${hasRole(#vars.role_admin)}" > IS ADMIN </div> <!-- Doesnt work -->
8.<div th:text="${#authorization.expression('hasRole(''ADMIN'')')} "></div> <!-- Doesnt work -->
9.<div th:text="${#authorization.expression('hasRole(#vars.role_admin)')}"></div> <!-- Doesnt work -->
Run Code Online (Sandbox Code Playgroud)
结果是:
1.admin
2.[ADMIN]
3.true
4.true
5.ADMIN
6."prints nothing …Run Code Online (Sandbox Code Playgroud) 有config(applicationContext-security.xml):
<authentication-manager alias="authenticationManager">
<authentication-provider>
<password-encoder hash="sha"/>
<jdbc-user-service data-source-ref="dataSource"/>
</authentication-provider>
</authentication-manager>
Run Code Online (Sandbox Code Playgroud)
从另一边有我的dataSource(这是JdbcDaoImpl)的SQL :
...
public static final String DEF_USERS_BY_USERNAME_QUERY =
"select username,password,enabled " +
"from users " +
"where username = ?";
...
Run Code Online (Sandbox Code Playgroud)
现在有关sha于此代码的消息,因此从标准Spring Security users表中选择的密码未编码.
也许,我应该在我的hibernate映射配置中sha为password列提供一些属性:
<class name="model.UserDetails" table="users">
<id name="id">
<generator class="increment"/>
</id>
<property name="username" column="username"/>
<property name="password" column="password"/>
<property name="enabled" column="enabled"/>
<property name="mail" column="mail"/>
<property name="city" column="city"/>
<property name="confirmed" column="confirmed"/>
<property name="confirmationCode" column="confirmation_code"/>
<set name="authorities" cascade="all" inverse="true"> …Run Code Online (Sandbox Code Playgroud)