- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个基本的 SpringBoot 2.0.5.RELEASE 应用程序。使用Spring Initializer、JPA、嵌入式Tomcat、Thymeleaf模板引擎,并打包为具有restful架构的可执行JAR
我已经创建了这个 Rest Controller 用于身份验证:
@RestController
public class AuthenticationRestController {
private static final Logger LOG = LoggerFactory.getLogger (AuthenticationRestController.class);
@Value("${jwt.header}")
private String tokenHeader;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private UserSecurityService userSecurityService;
@RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest) throws AuthenticationException {
LOG.info("authenticating [ " + authenticationRequest.getUsername() + " ]");
authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
// Reload password post-security so we can generate the token
final UserDetails userDetails = userSecurityService.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails);
// Return the token
return ResponseEntity.ok(new JwtAuthenticationResponse(token));
}
@RequestMapping(value = "${jwt.route.authentication.refresh}", method = RequestMethod.GET)
public ResponseEntity<?> refreshAndGetAuthenticationToken(HttpServletRequest request) {
String authToken = request.getHeader(tokenHeader);
final String token = authToken.substring(7);
String username = jwtTokenUtil.getUsernameFromToken(token);
JwtUser user = (JwtUser) userSecurityService.loadUserByUsername(username);
if (jwtTokenUtil.canTokenBeRefreshed(token, user.getLastPasswordResetDate())) {
String refreshedToken = jwtTokenUtil.refreshToken(token);
return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
} else {
return ResponseEntity.badRequest().body(null);
}
}
@ExceptionHandler({AuthenticationException.class})
public ResponseEntity<String> handleAuthenticationException(AuthenticationException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
}
/**
* Authenticates the user. If something is wrong, an {@link AuthenticationException} will be thrown
*/
private void authenticate(String username, String password) {
Objects.requireNonNull(username);
Objects.requireNonNull(password);
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
} catch (DisabledException e) {
throw new AuthenticationException("User is disabled!", e);
} catch (BadCredentialsException e) {
throw new AuthenticationException("Bad credentials!", e);
}
}
}
这个配置文件来管理配置
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter {
//private static final Logger LOG = LoggerFactory.getLogger(ApiWebSecurityConfig.class);
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private UserSecurityService userSecurityService;
@Value("${jwt.header}")
private String tokenHeader;
@Value("${jwt.route.authentication.path}")
private String authenticationPath;
@Value("${server.servlet.context-path}")
private String serverContextPath;
/** The encryption SALT. */
private static final String SALT = "f13333";
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userSecurityService)
.passwordEncoder(passwordEncoder());
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12, new SecureRandom(SALT.getBytes()));
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// we don't need CSRF because our token is invulnerable
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
// don't create session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
// Un-secure H2 Database
.antMatchers("/h2-console/**/**").permitAll()
.antMatchers("/auth/**").permitAll()
.anyRequest().authenticated();
// Custom JWT based security filter
JwtAuthorizationTokenFilter authenticationTokenFilter = new JwtAuthorizationTokenFilter(userDetailsService(), jwtTokenUtil, tokenHeader);
httpSecurity
.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
// disable page caching
httpSecurity
.headers()
.frameOptions().sameOrigin() // required to set for H2 else H2 Console will be blank.
.cacheControl();
}
@Override
public void configure(WebSecurity web) throws Exception {
// AuthenticationTokenFilter will ignore the below paths
web
.ignoring()
.antMatchers(
HttpMethod.POST,
authenticationPath
)
}
}
但是当我将这个curl放入我的计算机的控制台时,在Ubuntu服务器中托管的服务器控制台中出现此错误:
url -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{"username":"nunet@gmail.com","password":"qwerty"}' "http://139.262.221.117:1234/calssada/api/v1/auth"
服务器日志:
2018-10-15 19:14 [http-nio-1234-exec-1] DEBUG o.a.coyote.http11.Http11InputBuffer - Received [POST /calssada/api/v1/auth HTTP/1.1
Host: 139.262.221.117:1234
User-Agent: curl/7.54.0
Accept: */*
Content-Type: application/json
Cache-Control: no-cache
Content-Length: 56
{"username":"nunet@gmail.com","password":"qwerty"}]
2018-10-15 19:14 [http-nio-1234-exec-1] DEBUG o.a.c.a.AuthenticatorBase - Security checking request POST /calssada/api/v1/auth
2018-10-15 19:14 [http-nio-1234-exec-1] DEBUG org.apache.catalina.realm.RealmBase - No applicable constraints defined
2018-10-15 19:14 [http-nio-1234-exec-1] DEBUG o.a.c.a.AuthenticatorBase - Not subject to any constraint
2018-10-15 19:14 [http-nio-1234-exec-1] DEBUG o.a.tomcat.util.http.Parameters - Set encoding to UTF-8
2018-10-15 19:14 [http-nio-1234-exec-1] DEBUG o.a.c.c.C.[Tomcat].[localhost] - Processing ErrorPage[errorCode=0, location=/error]
2018-10-15 19:14 [http-nio-1234-exec-1] DEBUG o.a.c.c.C.[.[.[.[dispatcherServlet] - Disabling the response for further output
2018-10-15 19:14 [http-nio-1234-exec-1] DEBUG o.a.t.util.net.SocketWrapperBase - Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@2fca076b:org.apache.tomcat.util.net.NioChannel@5c80e3a0:java.nio.channels.SocketChannel[connected local=/139.262.221.117:1234 remote=/119.88.31.26:58071]], Read from buffer: [0]
2018-10-15 19:14 [http-nio-1234-exec-1] DEBUG o.a.tomcat.util.net.NioEndpoint - Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@2fca076b:org.apache.tomcat.util.net.NioChannel@5c80e3a0:java.nio.channels.SocketChannel[connected local=/139.262.221.117:1234 remote=/119.88.31.26:58071]], Read direct from socket: [0]
2018-10-15 19:14 [http-nio-1234-exec-1] DEBUG o.a.coyote.http11.Http11Processor - Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@2fca076b:org.apache.tomcat.util.net.NioChannel@5c80e3a0:java.nio.channels.SocketChannel[connected local=/139.262.221.117:1234 remote=/119.88.31.26:58071]], Status in: [OPEN_READ], State out: [OPEN]
2018-10-15 19:14 [http-nio-1234-exec-1] DEBUG o.a.coyote.http11.Http11NioProtocol - Pushed Processor [org.apache.coyote.http11.Http11Processor@28de9baa]
2018-10-15 19:14 [http-nio-1234-exec-2] DEBUG o.a.coyote.http11.Http11NioProtocol - Processing socket [org.apache.tomcat.util.net.NioChannel@5c80e3a0:java.nio.channels.SocketChannel[connected local=/139.262.221.117:1234 remote=/119.88.31.26:58071]] with status [OPEN_READ]
2018-10-15 19:14 [http-nio-1234-exec-2] DEBUG o.a.coyote.http11.Http11NioProtocol - Found processor [null] for socket [org.apache.tomcat.util.net.NioChannel@5c80e3a0:java.nio.channels.SocketChannel[connected local=/139.262.221.117:1234 remote=/119.88.31.26:58071]]
2018-10-15 19:14 [http-nio-1234-exec-2] DEBUG o.a.coyote.http11.Http11NioProtocol - Popped processor [org.apache.coyote.http11.Http11Processor@28de9baa] from cache
2018-10-15 19:14 [http-nio-1234-exec-2] DEBUG o.a.t.util.net.SocketWrapperBase - Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@2fca076b:org.apache.tomcat.util.net.NioChannel@5c80e3a0:java.nio.channels.SocketChannel[connected local=/139.262.221.117:1234 remote=/119.88.31.26:58071]], Read from buffer: [0]
2018-10-15 19:14 [http-nio-1234-exec-2] DEBUG o.a.coyote.http11.Http11Processor - Error parsing HTTP request header
java.io.EOFException: null
at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.fillReadBuffer(NioEndpoint.java:1289)
at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.read(NioEndpoint.java:1223)
at org.apache.coyote.http11.Http11InputBuffer.fill(Http11InputBuffer.java:729)
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:368)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:684)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
2018-10-15 19:14 [http-nio-1234-exec-2] DEBUG o.a.coyote.http11.Http11Processor - Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@2fca076b:org.apache.tomcat.util.net.NioChannel@5c80e3a0:java.nio.channels.SocketChannel[connected local=/139.262.221.117:1234 remote=/119.88.31.26:58071]], Status in: [OPEN_READ], State out: [CLOSED]
最佳答案
也许您必须将 -H "Connection: close"
添加到 curl
命令中?
请注意,您的错误日志中有两个请求。第一个由线程“http-nio-1234-exec-1”处理。我想知道“Processing ErrorPage[errorCode=0, location=/error]”是否意味着它导致了失败。
HTTP/1.1 协议(protocol)允许通过同一连接发送多个请求(也称为 Keep-Alive)。由于没有“Connection: close” header ,Tomcat 继续从连接读取。这是由线程“http-nio-1234-exec-2”执行的,并且在尝试读取请求的第一行 (Http11InputBuffer.parseRequestLine()
) 时失败并出现 EOF。这里预计会出现 EOF。
关于java - 调用 Rest 身份验证 Controller 时出现 EOFException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52823567/
SQLite、Content provider 和 Shared Preference 之间的所有已知区别。 但我想知道什么时候需要根据情况使用 SQLite 或 Content Provider 或
警告:我正在使用一个我无法完全控制的后端,所以我正在努力解决 Backbone 中的一些注意事项,这些注意事项可能在其他地方更好地解决......不幸的是,我别无选择,只能在这里处理它们! 所以,我的
我一整天都在挣扎。我的预输入搜索表达式与远程 json 数据完美配合。但是当我尝试使用相同的 json 数据作为预取数据时,建议为空。点击第一个标志后,我收到预定义消息“无法找到任何内容...”,结果
我正在制作一个模拟 NHL 选秀彩票的程序,其中屏幕右侧应该有一个 JTextField,并且在左侧绘制弹跳的选秀球。我创建了一个名为 Ball 的类,它实现了 Runnable,并在我的主 Draf
这个问题已经有答案了: How can I calculate a time span in Java and format the output? (18 个回答) 已关闭 9 年前。 这是我的代码
我有一个 ASP.NET Web API 应用程序在我的本地 IIS 实例上运行。 Web 应用程序配置有 CORS。我调用的 Web API 方法类似于: [POST("/API/{foo}/{ba
我将用户输入的时间和日期作为: DatePicker dp = (DatePicker) findViewById(R.id.datePicker); TimePicker tp = (TimePic
放宽“邻居”的标准是否足够,或者是否有其他标准行动可以采取? 最佳答案 如果所有相邻解决方案都是 Tabu,则听起来您的 Tabu 列表的大小太长或您的释放策略太严格。一个好的 Tabu 列表长度是
我正在阅读来自 cppreference 的代码示例: #include #include #include #include template void print_queue(T& q)
我快疯了,我试图理解工具提示的行为,但没有成功。 1. 第一个问题是当我尝试通过插件(按钮 1)在点击事件中使用它时 -> 如果您转到 Fiddle,您会在“内容”内看到该函数' 每次点击都会调用该属
我在功能组件中有以下代码: const [ folder, setFolder ] = useState([]); const folderData = useContext(FolderContex
我在使用预签名网址和 AFNetworking 3.0 从 S3 获取图像时遇到问题。我可以使用 NSMutableURLRequest 和 NSURLSession 获取图像,但是当我使用 AFHT
我正在使用 Oracle ojdbc 12 和 Java 8 处理 Oracle UCP 管理器的问题。当 UCP 池启动失败时,我希望关闭它创建的连接。 当池初始化期间遇到 ORA-02391:超过
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 9 年前。 Improve
引用这个plunker: https://plnkr.co/edit/GWsbdDWVvBYNMqyxzlLY?p=preview 我在 styles.css 文件和 src/app.ts 文件中指定
为什么我的条形这么细?我尝试将宽度设置为 1,它们变得非常厚。我不知道还能尝试什么。默认厚度为 0.8,这是应该的样子吗? import matplotlib.pyplot as plt import
当我编写时,查询按预期执行: SELECT id, day2.count - day1.count AS diff FROM day1 NATURAL JOIN day2; 但我真正想要的是右连接。当
我有以下时间数据: 0 08/01/16 13:07:46,335437 1 18/02/16 08:40:40,565575 2 14/01/16 22:2
一些背景知识 -我的 NodeJS 服务器在端口 3001 上运行,我的 React 应用程序在端口 3000 上运行。我在 React 应用程序 package.json 中设置了一个代理来代理对端
我面临着一个愚蠢的问题。我试图在我的 Angular 应用程序中延迟加载我的图像,我已经尝试过这个2: 但是他们都设置了 src attr 而不是 data-src,我在这里遗漏了什么吗?保留 d
我是一名优秀的程序员,十分优秀!