配置登录安全验证接口返回JSON数据

This commit is contained in:
lu 2025-01-15 21:48:20 +08:00
parent b93aa6f844
commit daae757628
15 changed files with 88 additions and 314 deletions

View File

@ -8,7 +8,7 @@
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<processorPath useClasspath="false">
<entry name="$MAVEN_REPOSITORY$/org/projectlombok/lombok/unknown/lombok-unknown.jar" />
<entry name="$MAVEN_REPOSITORY$/org/projectlombok/lombok/1.18.26/lombok-1.18.26.jar" />
</processorPath>
<module name="study-project-backend" />
</profile>

12
node_modules/.package-lock.json generated vendored
View File

@ -1,12 +0,0 @@
{
"name": "study-project",
"lockfileVersion": 2,
"requires": true,
"packages": {
"node_modules/fast-clone": {
"version": "1.5.13",
"resolved": "https://registry.npmjs.org/fast-clone/-/fast-clone-1.5.13.tgz",
"integrity": "sha512-0ez7coyFBQFjZtId+RJqJ+EQs61w9xARfqjqK0AD9vIUkSxWD4HvPt80+5evebZ1tTnv1GYKrPTipx7kOW5ipA=="
}
}
}

View File

@ -1,46 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at codeandcats@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@ -1,19 +0,0 @@
# Contributing
When contributing to this repository, please first discuss the change you wish to make via issue,
email, or any other method with the owners of this repository before making a change.
Please note we have a [code of conduct](CODE_OF_CONDUCT.md), please follow it in all your interactions with the project.
## Commit Message Convention
This project uses commit lint to force conventional commit messages. Please use `npm run commit` to commit your code, ensuring when prompted to use an [allowed change type](https://gist.github.com/stephenparish/9941e89d80e2bc58a153#allowed-type).
## Pull Request Process
1. Ensure that any new or altered code is covered by unit tests.
2. Update the README.md with details of changes to the interface, this includes new environment
variables, exposed ports, useful file locations and container parameters.

21
node_modules/fast-clone/LICENSE generated vendored
View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2019 Ben Daniel <codeandcats@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

85
node_modules/fast-clone/README.md generated vendored
View File

@ -1,85 +0,0 @@
<center>
<img src="https://raw.githubusercontent.com/codeandcats/fast-clone/master/logo.png" />
</center>
[![npm version](https://badge.fury.io/js/fast-clone.svg)](https://badge.fury.io/js/fast-clone)
[![Build Status](https://travis-ci.org/codeandcats/fast-clone.svg?branch=master)](https://travis-ci.org/codeandcats/fast-clone)
[![Coverage Status](https://coveralls.io/repos/github/codeandcats/fast-clone/badge.svg?branch=master)](https://coveralls.io/github/codeandcats/fast-clone?branch=master)
[![Greenkeeper badge](https://badges.greenkeeper.io/codeandcats/fast-clone.svg)](https://greenkeeper.io/)
The ***fastest deep cloning*** function on NPM that supports the following types:
- Objects (POJOs, null, undefined)
- Arrays
- Dates
- Regular Expressions
- Strings
- Numbers (NaN, Positive Infinity, Negative Infinity)
- Booleans
## Speed Comparison
Average runtime of various NPM clone libraries on a **large** complex object loaded from json files of varying sizes ranging from 3.5 MB to 15 MB.
Library | 7.15 MB |
-------------------|------------|
**fast-clone** | **120 ms** |
✘ deepClone | 138 ms |
✘ lodash.cloneDeep | 155 ms |
✘ snapshot | 1,127 ms |
✘ angular.copy | 1,942 ms |
✘ clone | 2,085 ms |
## Installation
### NPM
```sh
npm install fast-clone --save
```
### Yarn
```sh
yarn add fast-clone
```
## Usage
Fast-clone is a UMD module so you can use it in Node.js, or in Browser either using Browserfy/Webpack, or by using the global clone function if not using a module loader.
### TypeScript
```ts
import clone = require('fast-clone');
```
### JavaScript
```js
const clone = require('fast-clone');
```
```ts
const a = {
name: 'Natasha Rominov',
age: 30,
skills: [
'Pistols',
'Espionage'
],
dateOfBirth: new Date('1986-05-21T00:00:00.000Z')
};
const b = clone(a);
b.skills.push('That grabby thing she does with her legs');
console.log(a.skills)
console.log(b.skills);
```
Output will be:
```ts
['Pistols', 'Espionage']
['Pistols', 'Espionage', 'That grabby thing she does with her legs']
```
## Contributing
Got an issue or a feature request? [Log it](https://github.com/codeandcats/fast-clone/issues).
[Pull-requests](https://github.com/codeandcats/fast-clone/pulls) are also welcome. 😸

5
node_modules/fast-clone/index.d.ts generated vendored
View File

@ -1,5 +0,0 @@
export as namespace clone;
export = clone;
declare function clone<T>(value: T): T;

91
node_modules/fast-clone/index.js generated vendored
View File

@ -1,91 +0,0 @@
"use strict";
var windowOrGlobal = Function('return this')();
(function (root) {
/* istanbul ignore next */
if (typeof exports !== 'undefined') {
/* istanbul ignore next */
if (typeof module !== 'undefined' && module && module.exports) {
exports = module.exports = clone;
}
exports.clone = clone;
}
else {
/* istanbul ignore next */
root.clone = clone;
}
function clone(value) {
var type = typeof value;
switch (type) {
case 'object':
// null and undefined
if (value == null) {
return value;
}
var result = void 0;
if (value instanceof Date) {
result = new Date();
result.setTime(value.getTime());
return result;
}
else if (value instanceof RegExp) {
result = newRegExp(value);
return result;
}
result = JSON.parse(JSON.stringify(value));
fixTypes(value, result);
return result;
default:
return value;
}
}
function fixPropertyValue(original, copy, key) {
var originalValue = original[key];
var originalType = typeof originalValue;
switch (originalType) {
case 'object':
if (originalValue instanceof Date) {
var newValue = new Date();
newValue.setTime(originalValue.getTime());
copy[key] = newValue;
}
else if (originalValue instanceof RegExp) {
copy[key] = newRegExp(originalValue);
}
else if (originalValue == null) {
copy[key] = originalValue;
}
else {
fixTypes(originalValue, copy[key]);
}
break;
case 'number':
if (isNaN(originalValue)) {
copy[key] = NaN;
}
else if (originalValue == Infinity) {
copy[key] = Infinity;
}
break;
default:
break;
}
}
function fixTypes(original, copy) {
if (original instanceof Array) {
for (var index = 0; index < original.length; index++) {
fixPropertyValue(original, copy, index);
}
}
else {
var keys = Object.getOwnPropertyNames(original);
keys.forEach(function (key) {
fixPropertyValue(original, copy, key);
});
}
}
function newRegExp(value) {
var regexpText = String(value);
var slashIndex = regexpText.lastIndexOf('/');
return new RegExp(regexpText.slice(1, slashIndex), regexpText.slice(slashIndex + 1));
}
})(windowOrGlobal);

28
node_modules/fast-clone/package.json generated vendored
View File

@ -1,28 +0,0 @@
{
"name": "fast-clone",
"version": "1.5.13",
"description": "Extremely fast deep cloning function",
"main": "./index.js",
"keywords": [
"clone",
"copy",
"deep",
"object",
"date",
"fast",
"fastest",
"quick",
"efficient"
],
"author": "Ben Daniel <codeandcats@gmail.com>",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/codeandcats/fast-clone.git"
},
"bugs": {
"url": "https://github.com/codeandcats/fast-clone/issues"
},
"homepage": "https://github.com/codeandcats/fast-clone#readme",
"types": "index.d.ts"
}

View File

@ -47,7 +47,6 @@
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
@ -91,6 +90,7 @@
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
</configuration>

View File

@ -2,23 +2,30 @@ package com.example.config;
import com.alibaba.fastjson2.JSONObject;
import com.example.entity.RestBean;
import jakarta.servlet.ServletException;
import com.example.service.AuthorizeService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import java.io.IOException;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
@Resource
AuthorizeService authorizeService;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
@ -41,13 +48,28 @@ public class SecurityConfiguration {
.and()
.build();
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity security) throws Exception {
return security
.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(authorizeService)
.and()
.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
public void onAuthenticationSuccess (HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException {
response.setCharacterEncoding("UTF-8");
// response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
response.getWriter().write(JSONObject.toJSONString(RestBean.success("登录成功!")));
}
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
// response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
response.getWriter().write(JSONObject.toJSONString(RestBean.failure(401, exception.getMessage())));
}
}

View File

@ -0,0 +1,11 @@
package com.example.entity;
import lombok.Data;
@Data
public class Account {
int id;
String email;
String username;
String password;
}

View File

@ -0,0 +1,11 @@
package com.example.mapper;
import com.example.entity.Account;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("select * from db_account where username = #{text} or email = #{text}")
Account findAccountByNameOrEmail(String text);
}

View File

@ -0,0 +1,33 @@
package com.example.service;
import com.example.entity.Account;
import com.example.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class AuthorizeService implements UserDetailsService {
@Resource
UserMapper mapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if(username == null){
throw new UsernameNotFoundException("用户名不能为空");
}
Account account = mapper.findAccountByNameOrEmail(username);
if(account == null) {
throw new UsernameNotFoundException("用户名或密码错误");
}
return User
.withUsername(account.getUsername())
.password(account.getPassword())
.roles("user")
.build();
}
}

View File

@ -2,12 +2,16 @@ package com.example;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@SpringBootTest
class StudyProjectBackendApplicationTests {
@Test
void contextLoads() {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
System.out.println(encoder.encode("123456"));
}
}