- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在构建一个 REST 端点来验证(登录)用户。我为此使用了自定义身份验证提供程序。
我的context.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:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<context:annotation-config />
<context:component-scan base-package="com.foobar" />
<bean id="authDao" class="com.foobar.security.ldap.AuthProviderImpl">
</bean>
<bean id="myAuthProvider" class="com.foobar.security.MyAuthProvider">
</bean>
<security:authentication-manager id="authenticationManager" alias="authenticationManager">
<security:authentication-provider ref="myAuthProvider" />
</security:authentication-manager>
<security:http
realm="Protected API"
use-expressions="true"
auto-config="false"
create-session="stateless"
entry-point-ref="unauthorizedEntryPoint"
authentication-manager-ref="authenticationManager">
<security:custom-filter ref="authenticationTokenProcessingFilter" position="FORM_LOGIN_FILTER" />
<security:intercept-url method="POST" pattern="/rest/autenticacion/login" access="permitAll" />
</security:http>
<bean id="unauthorizedEntryPoint" class="com.foobar.security.UnauthorizedEntryPoint" />
<bean id="authenticationTokenProcessingFilter" class="com.foobar.security.AuthenticationTokenProcessingFilter">
<constructor-arg ref="authDao" />
</bean>
</beans>
我的自定义身份验证提供程序(myAuthProvider)的定义如下
package com.foobar.security;
import java.util.ResourceBundle;
import javax.inject.Inject;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@Component
public class MyAuthProvider implements AuthenticationProvider {
private final ResourceBundle properties = ResourceBundle.getBundle("security");
@Inject
private UserDetailsService authDao;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String)authentication.getCredentials();
if (username.equals("admin") && password.equals("admin")) {
UserDetails userDetails = this.authDao.loadUserByUsername(username);
return new UsernamePasswordAuthenticationToken(username, password, userDetails.getAuthorities());
} else {
throw new BadCredentialsException("Bad username or password");
}
}
@Override
public boolean supports(Class<?> type) {
return true;
}
}
我的AuthProviderImpl类如下
package com.foobar.security.ldap;
import com.foobar.security.AuthProvider;
import java.util.Arrays;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
@Component
public class AuthProviderImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if (username.equals("admin")) {
return new UserDetailsImpl("admin", Arrays.asList(new String[] { "ADMIN" }));
} else {
throw new UsernameNotFoundException("User not found");
}
}
}
我的UserDetailsImpl类如下
package com.foobar.security.ldap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
public class UserDetailsImpl implements UserDetails {
private final String username;
private final Date accountExpirationDate;
private final Boolean locked;
private final Date credentialsExpirationDate;
private final Boolean enabled;
private final List<String> roles;
public UserDetailsImpl(String username, Date accountExpirationDate, Boolean locked, Date credentialsExpirationDate, Boolean enabled, List<String> roles) {
this.username = username;
this.accountExpirationDate = accountExpirationDate;
this.locked = locked;
this.credentialsExpirationDate = credentialsExpirationDate;
this.enabled = enabled;
this.roles = roles;
}
public UserDetailsImpl(String username, List<String> roles) {
this.username = username;
this.accountExpirationDate = null;
this.locked = false;
this.credentialsExpirationDate = null;
this.enabled = true;
this.roles = roles;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> rolList = new ArrayList<GrantedAuthority>(this.roles.size());
for (String role : this.roles) {
rolList.add(new SimpleGrantedAuthority(role));
}
return rolList;
}
@Override
public String getPassword() {
return "";
}
@Override
public String getUsername() {
return this.username;
}
@Override
public boolean isAccountNonExpired() {
return this.accountExpirationDate != null && this.accountExpirationDate.after(new Date());
}
@Override
public boolean isAccountNonLocked() {
return !this.locked;
}
@Override
public boolean isCredentialsNonExpired() {
return this.credentialsExpirationDate != null && this.credentialsExpirationDate.after(new Date());
}
@Override
public boolean isEnabled() {
return this.enabled;
}
}
最后是我的 REST 端点
package com.foobar.rest;
import com.foobar.rest.dto.AutenticacionDTO;
import com.foobar.security.AuthProvider;
import com.foobar.security.TokenUtils;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
@Component
@Path("/autenticacion")
public class AutenticacionEndpoint {
private static final Logger logger = Logger.getLogger(AutenticacionEndpoint.class);
@Inject
private AuthProvider authDao;
@Autowired
@Qualifier("authenticationManager")
private AuthenticationManager authenticationManager;
@POST
@Path("login")
@Consumes("application/json")
public Response autenticar(AutenticacionDTO datos) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(datos.getUsuario(), datos.getClave());
AutenticacionDTO response;
UserDetails userDetails = null;
try {
userDetails = this.authDao.loadUserByUsername(datos.getUsuario());
/// THIS PART FAILS SINCE this.authenticationManager equals NULL - NullPointerException
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
Map<String, Boolean> roles = new HashMap<String, Boolean>(authentication.getAuthorities().size());
for (GrantedAuthority auth : authentication.getAuthorities()) {
roles.put(auth.getAuthority(), Boolean.TRUE);
}
response = new AutenticacionDTO(userDetails.getUsername(), Boolean.TRUE, null, null, TokenUtils.createToken(userDetails), !userDetails.isAccountNonExpired(), !userDetails.isCredentialsNonExpired());
return Response.status(Response.Status.OK).entity(response).build();
} catch (AuthenticationException ex) {
if (userDetails != null) {
response = new AutenticacionDTO(datos.getUsuario(), "Fallo en autenticacion", !userDetails.isAccountNonExpired(), !userDetails.isCredentialsNonExpired());
} else {
response = new AutenticacionDTO(datos.getUsuario(), false, "Usuario o contraseña inválidos");
}
return Response.status(Response.Status.UNAUTHORIZED).entity(response).build();
}
}
}
为什么不是 authenticationManager
在终点注入(inject)?在最后一个类中,我还将“authDao”设置为 @Autowired
但它也没有被注入(inject),直到我将其替换为 @Inject
注解。但我不能使用@Inject
与 authenticationManager
因为它不能将其识别为 bean。
有什么想法吗?
最佳答案
我不知道为什么,但 Spring bean 没有像我的自定义类那样被注入(inject)。我通过做一件“肮脏”的事情解决了这个问题。在 REST 端点的 autenticar
方法中,我添加了以下代码:
@Path("login")
@Consumes("application/json")
public Response autenticar(AutenticacionDTO datos, @Context ServletContext servletContext) {
logger.trace("AutenticacionEndpoint - autenticar");
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(datos.getUsuario(), datos.getClave());
AutenticacionDTO response;
UserDetails userDetails = null;
try {
userDetails = this.authDao.loadUserByUsername(datos.getUsuario());
if (this.authenticationManager == null) {
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
this.authenticationManager = ctx.getBean("authenticationManager", AuthenticationManager.class);
}
...
我希望这对某人有帮助,或者也许有人有更好的选择。
关于java - Spring 的 AuthenticationManager 未正确注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24066512/
我正在尝试测试依赖于其他服务 authService 的服务 documentViewer angular .module('someModule') .service('docu
如果我的网站上线(不要认为它会,目前它只是一个学习练习)。 我一直在使用 mysql_real_escape_string();来自 POST、SERVER 和 GET 的数据。另外,我一直在使用 i
我有以下代码,它容易受到 SQL 注入(inject)的攻击(我认为?): $IDquery = mysqli_query($connection, "SELECT `ID` FROM users W
我一直在自学如何创建扩展,以期将它们用于 CSS 注入(inject)(以及最终以 CSS 为载体的 SVG 注入(inject),但那是以后的问题)。 这是我当前的代码: list .json {
这个简单的代码应该通过 Java Spring 实现一个简单的工厂。然而结果是空指针,因为 Human 对象没有被注入(inject)对象(所以它保持空)。 我做错了什么? 谢谢 配置 @Config
我正在编写一个 ASP.NET MVC4 应用程序,它最终会动态构建一个 SQL SELECT 语句,以便稍后存储和执行。动态 SQL 的结构由用户配置以用户友好的方式确定,具有标准复选框、下拉列表和
首先让我说我是我为确保 SQL 注入(inject)攻击失败而采取的措施的知己。所有 SQL 查询值都是通过事件记录准备语句完成的,所有运算符(如果不是硬编码)都是通过数字白名单系统完成的。这意味着如
这是 SQL 映射声称可注入(inject)的负载: user=-5305' UNION ALL SELECT NULL,CONCAT(0x716b6b7071,0x4f5577454f76734
我正在使用 Kotlin 和 Android 架构组件(ViewModel、LiveData)构建一个新的 Android 应用程序的架构,并且我还使用 Koin 作为我的依赖注入(inject)提供
假设 RequestScope 处于 Activity 状态(使用 cdi-unit 的 @InRequestScope) 给定 package at.joma.stackoverflow.cdi;
我有一个搜索表单,可以在不同的提供商中搜索。 我从拥有一个基本 Controller 开始 public SearchController : Controller { protected r
SQLite 注入 如果您的站点允许用户通过网页输入,并将输入内容插入到 SQLite 数据库中,这个时候您就面临着一个被称为 SQL 注入的安全问题。本章节将向您讲解如何防止这种情况的发生,确保脚
我可以从什么 dll 中获得 Intercept 的扩展?我从 http://github.com/danielmarbach/ninject.extensions.interception 添加了
使用 NInject 解析具有多个构造函数的类似乎不起作用。 public class Class1 : IClass { public Class1(int param) {...} public
我有一个 MetaManager 类: @Injectable() export class MetaManager{ constructor(private handlers:Handler
我是 Angular 的新手,我不太清楚依赖注入(inject)是如何工作的。我的问题是我有依赖于服务 B 的服务 A,但是当我将服务 A 注入(inject)我的测试服务 B 时,服务 B 变得未定
我正在为我的项目使用 android 应用程序启动、刀柄和空间。我在尝试排队工作时遇到错误: com.test E/WM-WorkerFactory: Could not instantiate co
我不确定这是什么糖语法,但让我向您展示问题所在。 def factors num (1..num).select {|n| num % n == 0} end def mutual_factors
简单的问题,我已经看过这个了:Managing imports in Scalaz7 ,但我不知道如何最小化注入(inject) right和 left方法到我的对象中以构造 \/ 的实例. 我确实尝
在我的 Aurelia SPA 中,我有一些我想在不同模块中使用的功能。它依赖于调用时给出的参数和单例的参数。有没有办法创建一个导出函数,我可以将我的 Auth 单例注入(inject)其中,而不必在
我是一名优秀的程序员,十分优秀!