Quantcast
Channel: ASP.NET Core
Viewing all 9386 articles
Browse latest View live

.net core console application forbidden access to https://..., a certificate is required

$
0
0

Hi pals,

I have a .net core console application and want to make a call to an API, hosted on an SSL-enabled endpoint. I have installed the certificate on my local machine, but still cannot call the api! I get the error "forbidden access tohttps://..., a certificate is required" How should I solve the issue? All previous issues regarding SSL I googled, are about asp.net core web app, whereas I have a .net core console app.

Parts of the code is here. I use RavenDb for my repository. The problem is that the raven server is hosted an SSL-based endpoint and I cannot get connected to it!

public static DocumentStore RavenDocumentStore { get; set; }
public static IEducationService EducationService { get; set; }

static async Task Main(string[] args)
{
            try
            {
				
				InitializeDatabases();
				InitializeService();
				
               var edu = new Education {
				   Id = 1,
				   Title = "Software Engineering"
			   };
			   await EducationService.AddAsync(edu);
               await EducationService.SaveChangesAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }

}
		
public static void InitializeDatabases()
{
            try
            {
                TbsContext = new TbsContext();
                RavenDocumentStore = new DocumentStore
                {
                    Urls = new[] { "https://someserver.com" },
                    Database = "test",
                    Conventions =
                    {
                        MaxNumberOfRequestsPerSession = int.MaxValue,
                    }
                };

                RavenDocumentStore.Initialize();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Logger.ErrorException(ex.Message, ex);
                throw;
            }
}		
		
private static void InitializeServices()
{
            try
            {
		var ravenAsyncSession = RavenDocumentStore.OpenAsyncSession();
				
                var educationRepository = new EducationRepository(ravenAsyncSession);
                EducationService = new EducationService(educationRepository);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Logger.ErrorException(ex.Message, ex);
                throw;
            }
}		

Thanks in advance


How to customize an operation object response?

$
0
0

What I am trying to do here is to custom a response object for my repository/service methods internally. I am talking about something like IdentityResult. 

    public class IdentityResult
    {
        public IdentityResult();
        public static IdentityResult Success { get; }
        public IEnumerable<IdentityError> Errors { get; }
        public static IdentityResult Failed(params IdentityError[] errors);
        public override string ToString();
    }

I started with something like,

    public class ApiMethodResponse {
        public ApiMethodResponse () {
            Errors = new List<string> ();
        }
        public bool Success { get; set; }
        public dynamic Value { get; set; }
        public List<string> Errors { get; set; }
    }

and I implement it like,

       private ApiMethodResponse IsValidCredentials (ApplicationUser user) {
            ApiMethodResponse method = new ApiMethodResponse ();
            if (string.IsNullOrWhiteSpace (user.UserName) && string.IsNullOrWhiteSpace (user.Email))

                return new ApiMethodResponse { Success = true };

            if (!string.IsNullOrWhiteSpace (user.UserName) && string.IsNullOrWhiteSpace (user.Email)) {
                method.Success = false;
                method.Errors.Add ("Invalid credentials, if user name is provided, email address should be provided as well!");
                return method;
            }
            if (string.IsNullOrWhiteSpace (user.UserName) && !string.IsNullOrWhiteSpace (user.Email)) {
                method.Success = false;
                method.Errors.Add ("Invalid credentials, if email address is provided, user name should be provided as well!");
                return method;
            }

            return new ApiMethodResponse { Success = true };
        }

is there a better way?

Thanks

Can't get validation message on int property

$
0
0

I have a model with this property:

[Required]      
[Range(1, 3, ErrorMessage = "This question needs to be set before you continue!")]
public int Question4 { get; set; }

but when the user submits the form i don't get this errormessage i wrote. istead i get "question4 is required", which i don't want. this is the form, which is radio buttons :

<div class="form-group"><div class="custom-control custom-radio custom-control-inline"><input type="radio" id="custom8" asp-for="Question4" class="custom-control-input" 
    value="1" required><label class="custom-control-label" for="custom8"></label></div><div class="custom-control custom-radio custom-control-inline"><input type="radio" id="custom9" asp-for="Question4" class="custom-control-input" 
    value="2" required><label class="custom-control-label" for="custom9"></label></div><div class="custom-control custom-radio custom-control-inline"><input type="radio" id="custom10" asp-for="Question4" class="custom-control-input" 
    value="3" required><label class="custom-control-label" for="custom10" ></label></div></div>

I can't put asp-for in the label because it won't work then. 

Any feedback would be much appreciated!

SSL redirection does not work

Issue WCF Web Service Asp.net core

$
0
0

ErrorHi all!

I used WCF Web Service Asp.net core with error, please can you help me?

System.NullReferenceException: Object reference not set to an instance of an object.

My code:

public void GetRelationShip()
{
ServiceReference1.WSForOtherSystemClient client = new ServiceReference1.WSForOtherSystemClient();
ServiceReference1.authorityBO authorityBO = new ServiceReference1.authorityBO();
authorityBO.userName = "***";
authorityBO.password = "***";

ServiceReference1.parameterBO para = new ServiceReference1.parameterBO();
para.name = "PROVINCE_CODE";
para.value = "BDG";
ServiceReference1.requestInputBO inputBO = new ServiceReference1.requestInputBO();
inputBO.code = "SQL_SON_GET_RELATION2";
inputBO.@params[0] = para;
var result = client.getDataJsonAsync(authorityBO, inputBO);
}


With wsdl:

<?xml version="1.0" encoding="UTF-8"?><!--Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is Metro/2.2 (branches/2.2-7015; 2012-02-20T20:31:25+0000) JAXWS-RI/2.2.6 JAXWS/2.2 svn-revision#unknown.--><!--Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is Metro/2.2 (branches/2.2-7015; 2012-02-20T20:31:25+0000) JAXWS-RI/2.2.6 JAXWS/2.2 svn-revision#unknown.--><definitions targetNamespace="http://webservice.viettel.com/" name="WSForOtherSystemService" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://webservice.viettel.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/"><types><xsd:schema><xsd:import namespace="http://webservice.viettel.com/" schemaLocation="WSForOtherSystem.xsd"/></xsd:schema></types><message name="getENodeBByProvince"><part name="userService" type="xsd:string"/><part name="passService" type="xsd:string"/><part name="provinceCode" type="xsd:string"/></message><message name="getENodeBByProvinceResponse"><part name="return" type="tns:resultEnodeB"/></message><message name="Exception"><part name="fault" element="tns:Exception"/></message><message name="getDataJson"><part name="authorityBO" type="tns:authorityBO"/><part name="requestInputBO" type="tns:requestInputBO"/></message><message name="getDataJsonResponse"><part name="return" type="tns:jsonResponseBO"/></message><portType name="WSForOtherSystem"><operation name="getENodeBByProvince" parameterOrder="userService passService provinceCode"><input wsam:Action="http://webservice.viettel.com/WSForOtherSystem/getENodeBByProvinceRequest" message="tns:getENodeBByProvince"/><output wsam:Action="http://webservice.viettel.com/WSForOtherSystem/getENodeBByProvinceResponse" message="tns:getENodeBByProvinceResponse"/><fault message="tns:Exception" name="Exception" wsam:Action="http://webservice.viettel.com/WSForOtherSystem/getENodeBByProvince/Fault/Exception"/></operation><operation name="getDataJson" parameterOrder="authorityBO requestInputBO"><input wsam:Action="http://webservice.viettel.com/WSForOtherSystem/getDataJsonRequest" message="tns:getDataJson"/><output wsam:Action="http://webservice.viettel.com/WSForOtherSystem/getDataJsonResponse" message="tns:getDataJsonResponse"/></operation></portType><binding name="WSForOtherSystemPortBinding" type="tns:WSForOtherSystem"><soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/><operation name="getENodeBByProvince"><soap:operation soapAction=""/><input><soap:body use="literal" namespace="http://webservice.viettel.com/"/></input><output><soap:body use="literal" namespace="http://webservice.viettel.com/"/></output><fault name="Exception"><soap:fault name="Exception" use="literal"/></fault></operation><operation name="getDataJson"><soap:operation soapAction=""/><input><soap:body use="literal" namespace="http://webservice.viettel.com/"/></input><output><soap:body use="literal" namespace="http://webservice.viettel.com/"/></output></operation></binding><service name="WSForOtherSystemService"><port name="WSForOtherSystemPort" binding="tns:WSForOtherSystemPortBinding"><soap:address location="http://10.60.97.112:8888/IPChangeProcess/WSForOtherSystem"/></port></service></definitions>
https://1drv.ms/u/s!AuEHHVKUJ7mKip1WyEmnt29MT89c0w

Image error

~/connect/token is not bein called properly

$
0
0

Hi,

My application is  not being logged in.  I am using the following source code.

https://github.com/emonney/QuickApp

and then upgraded the same source in angular 6, install angular material 6  and tried to use its components.

The problem is actually the app is not being logged in.  Method is unable to call. Sometimes function is being called properly and sometimes throwing errors.

Error is this :

Failed to load resource: the server responded with a status of 404 (Not Found)
alert.service.ts:154 Severity: "error", Summary: "Unable to login", Detail: "An error occured whilst logging in, please try again later.
Error: Not Found", Error: "{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":404,"statusText":"Not Found","url":"http://localhost:4200/connect/token","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost:4200/connect/token: 404 Not Found","error":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot POST /connect/token</pre>\n</body>\n</html>\n"}"

 // add identity
            services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            // Configure Identity options and password complexity here
            services.Configure<IdentityOptions>(options =>
            {
                // User settings
                options.User.RequireUniqueEmail = true;
                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
            });


 // Register the OpenIddict services.
            services.AddOpenIddict(options =>
            {
                options.AddEntityFrameworkCoreStores<ApplicationDbContext>();
                options.AddMvcBinders();
                options.EnableTokenEndpoint("/connect/token");
                options.AllowPasswordFlow();
                options.AllowRefreshTokenFlow();
                options.DisableHttpsRequirement();
            });



            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = OAuthValidationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OAuthValidationDefaults.AuthenticationScheme;
            }).AddOAuthValidation();



            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "SaleStoreAppUI API", Version = "v1" });

                c.AddSecurityDefinition("OpenID Connect", new OAuth2Scheme
                {
                    Type = "oauth2",
                    Flow = "password",
                    TokenUrl = "/connect/token"
                });
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy(Authorization.Policies.ViewAllUsersPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ViewUsers));
                options.AddPolicy(Authorization.Policies.ManageAllUsersPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ManageUsers));

                options.AddPolicy(Authorization.Policies.ViewAllRolesPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ViewRoles));
                options.AddPolicy(Authorization.Policies.ViewRoleByRoleNamePolicy, policy => policy.Requirements.Add(new ViewRoleAuthorizationRequirement()));
                options.AddPolicy(Authorization.Policies.ManageAllRolesPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ManageRoles));

                options.AddPolicy(Authorization.Policies.AssignAllowedRolesPolicy, policy => policy.Requirements.Add(new AssignRolesAuthorizationRequirement()));
            });

            Mapper.Initialize(cfg =>
            {
                cfg.AddProfile<AutoMapperProfile>();
            });
-------------------------------Authorization Controller----------------------------------------

[HttpPost("~/connect/token")]
[Produces("application/json")]
public async Task<IActionResult> Exchange(OpenIdConnectRequest request)
{
if (request.IsPasswordGrantType())
{
var user = await _userManager.FindByEmailAsync(request.Username) ?? await _userManager.FindByNameAsync(request.Username);
if (user == null)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "Please check that your email and password is correct"
});
}

// Ensure the user is enabled.
if (!user.IsEnabled)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The specified user account is disabled"
});
}


// Validate the username/password parameters and ensure the account is not locked out.
var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, true);

// Ensure the user is not already locked out.
if (result.IsLockedOut)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The specified user account has been suspended"
});
}

// Reject the token request if two-factor authentication has been enabled by the user.
if (result.RequiresTwoFactor)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "Invalid login procedure"
});
}

// Ensure the user is allowed to sign in.
if (result.IsNotAllowed)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The specified user is not allowed to sign in"
});
}

if (!result.Succeeded)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "Please check that your email and password is correct"
});
}

// Create a new authentication ticket.
var ticket = await CreateTicketAsync(request, user);

return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
else if (request.IsRefreshTokenGrantType())
{
// Retrieve the claims principal stored in the refresh token.
var info = await HttpContext.AuthenticateAsync(OpenIdConnectServerDefaults.AuthenticationScheme);

// Retrieve the user profile corresponding to the refresh token.
// Note: if you want to automatically invalidate the refresh token
// when the user password/roles change, use the following line instead:
// var user = _signInManager.ValidateSecurityStampAsync(info.Principal);
var user = await _userManager.GetUserAsync(info.Principal);
if (user == null)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The refresh token is no longer valid"
});
}

// Ensure the user is still allowed to sign in.
if (!await _signInManager.CanSignInAsync(user))
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The user is no longer allowed to sign in"
});
}

// Create a new authentication ticket, but reuse the properties stored
// in the refresh token, including the scopes originally granted.
var ticket = await CreateTicketAsync(request, user);

return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
ErrorDescription = "The specified grant type is not supported"
});
}

-----------------------------auth.service.ts--------------------------------------------------------------------

// ====================================================
// More Templates: https://www.ebenmonney.com/templates
// Email: support@ebenmonney.com
// ====================================================

import { Injectable } from '@angular/core';
import { Router, NavigationExtras } from "@angular/router";
import { Observable , Subject } from 'rxjs';


import { LocalStoreManager } from './local-store-manager.service';
import { EndpointFactory } from './endpoint-factory.service';
import { ConfigurationService } from './configuration.service';
import { DBkeys } from './db-Keys';
import { JwtHelper } from './jwt-helper';
import { Utilities } from './utilities';
import { LoginResponse, IdToken } from '../models/login-response.model';
import { User } from '../models/user.model';
import { Permission, PermissionNames, PermissionValues } from '../models/permission.model';

@Injectable()
export class AuthService {

public get loginUrl() { return this.configurations.loginUrl; }
public get homeUrl() { return this.configurations.homeUrl; }

public loginRedirectUrl: string;
public logoutRedirectUrl: string;

public reLoginDelegate: () => void;

private previousIsLoggedInCheck = false;
private _loginStatus = new Subject<boolean>();


constructor(private router: Router, private configurations: ConfigurationService, private endpointFactory: EndpointFactory, private localStorage: LocalStoreManager) {
this.initializeLoginStatus();
}


private initializeLoginStatus() {
this.localStorage.getInitEvent().subscribe(() => {
this.reevaluateLoginStatus();
});
}


gotoPage(page: string, preserveParams = true) {

let navigationExtras: NavigationExtras = {
queryParamsHandling: preserveParams ? "merge" : "", preserveFragment: preserveParams
};


this.router.navigate([page], navigationExtras);
}


redirectLoginUser() {
let redirect = this.loginRedirectUrl && this.loginRedirectUrl != '/' && this.loginRedirectUrl != ConfigurationService.defaultHomeUrl ? this.loginRedirectUrl : this.homeUrl;
this.loginRedirectUrl = null;


let urlParamsAndFragment = Utilities.splitInTwo(redirect, '#');
let urlAndParams = Utilities.splitInTwo(urlParamsAndFragment.firstPart, '?');

let navigationExtras: NavigationExtras = {
fragment: urlParamsAndFragment.secondPart,
queryParams: Utilities.getQueryParamsFromString(urlAndParams.secondPart),
queryParamsHandling: "merge"
};

this.router.navigate([urlAndParams.firstPart], navigationExtras);
}


redirectLogoutUser() {
let redirect = this.logoutRedirectUrl ? this.logoutRedirectUrl : this.loginUrl;
this.logoutRedirectUrl = null;

this.router.navigate([redirect]);
}


redirectForLogin() {
this.loginRedirectUrl = this.router.url;
this.router.navigate([this.loginUrl]);
}


reLogin() {

this.localStorage.deleteData(DBkeys.TOKEN_EXPIRES_IN);

if (this.reLoginDelegate) {
this.reLoginDelegate();
}
else {
this.redirectForLogin();
}
}


refreshLogin() {
return this.endpointFactory.getRefreshLoginEndpoint<LoginResponse>()
.map(response => this.processLoginResponse(response, this.rememberMe));
}


login(userName: string, password: string, rememberMe?: boolean) {

if (this.isLoggedIn)
this.logout();

return this.endpointFactory.getLoginEndpoint<LoginResponse>(userName, password)
.map(
response =>
this.processLoginResponse(response, rememberMe)
);
}


private processLoginResponse(response: LoginResponse, rememberMe: boolean) {
debugger;
let accessToken = response.access_token;

if (accessToken == null)
throw new Error("Received accessToken was empty");

let idToken = response.id_token;
let refreshToken = response.refresh_token || this.refreshToken;
let expiresIn = response.expires_in;

let tokenExpiryDate = new Date();
tokenExpiryDate.setSeconds(tokenExpiryDate.getSeconds() + expiresIn);

let accessTokenExpiry = tokenExpiryDate;

let jwtHelper = new JwtHelper();
let decodedIdToken = <IdToken>jwtHelper.decodeToken(response.id_token);

let permissions: PermissionValues[] = Array.isArray(decodedIdToken.permission) ? decodedIdToken.permission : [decodedIdToken.permission];

if (!this.isLoggedIn)
this.configurations.import(decodedIdToken.configuration);

let user = new User(
decodedIdToken.sub,
decodedIdToken.name,
decodedIdToken.fullname,
decodedIdToken.email,
decodedIdToken.jobtitle,
decodedIdToken.phone,
Array.isArray(decodedIdToken.role) ? decodedIdToken.role : [decodedIdToken.role]);
user.isEnabled = true;

this.saveUserDetails(user, permissions, accessToken, idToken, refreshToken, accessTokenExpiry, rememberMe);

this.reevaluateLoginStatus(user);

return user;
}


private saveUserDetails(user: User, permissions: PermissionValues[], accessToken: string, idToken: string, refreshToken: string, expiresIn: Date, rememberMe: boolean) {

if (rememberMe) {
this.localStorage.savePermanentData(accessToken, DBkeys.ACCESS_TOKEN);
this.localStorage.savePermanentData(idToken, DBkeys.ID_TOKEN);
this.localStorage.savePermanentData(refreshToken, DBkeys.REFRESH_TOKEN);
this.localStorage.savePermanentData(expiresIn, DBkeys.TOKEN_EXPIRES_IN);
this.localStorage.savePermanentData(permissions, DBkeys.USER_PERMISSIONS);
this.localStorage.savePermanentData(user, DBkeys.CURRENT_USER);
}
else {
this.localStorage.saveSyncedSessionData(accessToken, DBkeys.ACCESS_TOKEN);
this.localStorage.saveSyncedSessionData(idToken, DBkeys.ID_TOKEN);
this.localStorage.saveSyncedSessionData(refreshToken, DBkeys.REFRESH_TOKEN);
this.localStorage.saveSyncedSessionData(expiresIn, DBkeys.TOKEN_EXPIRES_IN);
this.localStorage.saveSyncedSessionData(permissions, DBkeys.USER_PERMISSIONS);
this.localStorage.saveSyncedSessionData(user, DBkeys.CURRENT_USER);
}

this.localStorage.savePermanentData(rememberMe, DBkeys.REMEMBER_ME);
}

logout(): void {
this.localStorage.deleteData(DBkeys.ACCESS_TOKEN);
this.localStorage.deleteData(DBkeys.ID_TOKEN);
this.localStorage.deleteData(DBkeys.REFRESH_TOKEN);
this.localStorage.deleteData(DBkeys.TOKEN_EXPIRES_IN);
this.localStorage.deleteData(DBkeys.USER_PERMISSIONS);
this.localStorage.deleteData(DBkeys.CURRENT_USER);

this.configurations.clearLocalChanges();

this.reevaluateLoginStatus();
}


private reevaluateLoginStatus(currentUser?: User) {

let user = currentUser || this.localStorage.getDataObject<User>(DBkeys.CURRENT_USER);
let isLoggedIn = user != null;

if (this.previousIsLoggedInCheck != isLoggedIn) {
setTimeout(() => {
this._loginStatus.next(isLoggedIn);
});
}

this.previousIsLoggedInCheck = isLoggedIn;
}


getLoginStatusEvent(): Observable<boolean> {
return this._loginStatus.asObservable();
}


get currentUser(): User {

let user = this.localStorage.getDataObject<User>(DBkeys.CURRENT_USER);
this.reevaluateLoginStatus(user);

return user;
}

get userPermissions(): PermissionValues[] {
return this.localStorage.getDataObject<PermissionValues[]>(DBkeys.USER_PERMISSIONS) || [];
}

get accessToken(): string {

this.reevaluateLoginStatus();
return this.localStorage.getData(DBkeys.ACCESS_TOKEN);
}

get accessTokenExpiryDate(): Date {

this.reevaluateLoginStatus();
return this.localStorage.getDataObject<Date>(DBkeys.TOKEN_EXPIRES_IN, true);
}

get isSessionExpired(): boolean {

if (this.accessTokenExpiryDate == null) {
return true;
}

return !(this.accessTokenExpiryDate.valueOf() > new Date().valueOf());
}


get idToken(): string {

this.reevaluateLoginStatus();
return this.localStorage.getData(DBkeys.ID_TOKEN);
}

get refreshToken(): string {

this.reevaluateLoginStatus();
return this.localStorage.getData(DBkeys.REFRESH_TOKEN);
}

get isLoggedIn(): boolean {
return this.currentUser != null;
}

get rememberMe(): boolean {
return this.localStorage.getDataObject<boolean>(DBkeys.REMEMBER_ME) == true;
}
}


Authorization controller----------------------------------------------------------------

[Razor Pages] Return partial view from code-behind?

$
0
0

My issue is straight-forward -- I have a list of items on my Index page.  When I click the 'edit' button next to an item, a modal window needs to pop up with a partial view form where I can edit the properties of the item.  I'm calling on the partial using a simple get-command with an id of the item.  This is where I'm lost, as I don't know how to return the partial view from the code-behind of the Index page.

// Index Page$.get('/Index?handler=EditPartial', { id: 5 }, function (result) {$('#modalBody').html(result);$('.modal').modal('open');
});

// Code-behind of Index

public IActionResult OnGetEditPartial(int id)
{
    var someModel = MyRepository.GetItem(id);

    // how to return a partial view page with 'someModel' ?
}

This seems so simple, but using the old method from MVC of "return PartialView('PageName', someModel);" is incorrect syntax for Razor Pages.  Is there a proper way to return a partial view/page ?

how to redirect to an action of other controller insde FileResult action

$
0
0

How to redirect to an action of other controller insde FileResult action, See the sample code below, If invalid user, not show the file, go to a message controller to show a message, and exit the FileResult action. How to do it? Thanks

<div>public FileResult DisplayFile()</div> <div>        {</div> <div>            if (IsValidUser == false)</div> <div>            {</div> <div>            go to a error page, and exit the current action</div><div>    }</div> <div>            byte[] pdfByte = GetFileByteDate();</div> <div> </div> <div>            return File(pdfByte, "application/pdf");</div> <div>        }</div>

Need to create a route that executes on return from OAuth 2.0 server

$
0
0

Hello,

I created an Asp.Net Core 2.0 client website, running locally, that makes a call to an OAuth 2.0 server.  The server returns a302 Redirect response, but the method on the client never executes.

Is there a special version of MapRoute that will redirect the client to a new location?

I tried this:

routes.MapRoute(
    name: "Process",
    template: "{controller=API}/{action=Process}");

and it gives a 404 Not Found on return.

Any help would be gratefully appreciated.

Thanks,
Tony

new version something is wrong in nuget package 2.1.0 for ASP.NET Core 2.1 Identity server

$
0
0

Hello 

I have just upgraded my test project and I had got this error (when I was trying login) . Microsoft.AspNetCore.All 2.1.0 - Microsoft.VisualStudio.Web.CodeGeneration.Design - 2.1.0

If I downgrade (demote) my project , there is no problem  Microsoft.AspNetCore.All 2.0.8

An unhandled exception occurred while processing the request.

<div class="titleerror">InvalidOperationException: Cannot create a DbSet for 'ApplicationUser' because this type is not included in the model for the context.</div>

Microsoft.EntityFrameworkCore.Internal.InternalDbSet<TEntity>.get_EntityType()

....................

MIS.WebUI.Controllers.SecurityController.Login(LoginViewModel loginViewModel, string returnUrl) in SecurityController.cs

<div class="source">
  1. ApplicationUser user = await UserManager.FindByEmailAsync(loginViewModel.Username);
</div>

hata

What is the proper way of using async/await?

$
0
0

I apologize for the long code,

this is my scenario. My application user table has one to one relationship with patient registry table. the following controller handles saving an object that contains both application user table data and patient registry table data as well.

in my controller, I have several tasks that are async and I am waiting for each one in order to get a success response and then move to another one.

i.e. 

 [HttpPut ("{FileId}")]
        public async Task<IActionResult> UpdatePatient ([FromRoute] PatientFileIdResource fileIdModel, [FromBody] SavePatientsRegistryResource model) {
PatientRegistry patient = await repository.GetPatient (fileIdModel.FileId.Value); here I get the patient,
            if (patient == null) {
                ModelState.AddModelError (string.Empty, "The patient does not exist in the database");
                return BadRequest (ModelState);
            } // handle null response (no patient)

// if things are fine

var isValidPartnerList = await this.repository.IsValidPartnerReseourceList (model.Partners.ToList ()); // I validate the collection

  if (!isValidPartnerList.Success) {
                foreach (string error in isValidPartnerList.Errors) {
                    ModelState.AddModelError (string.Empty, error);
                }

                return BadRequest (ModelState);
            } // handle Invalid entry in the collection

// if things are fine

I Do several mappings

var updateUser = await this.applicationUserRepository.UpdateUserAsync (modelPatientUserData); // update application user data

  if (updateUser.Success) { // if successfull
                await this.repository.UpdatePartnerCollection (storedPartnersList, patientPartnersModelDataList); // update patient data
                await unitOfWork.CompleteAsync (header); // save 
                await SendConfirmation (modelPatientUserData); // send conf email
                response.SuccessMessages.Add (patient.User.FirstName + " " + patient.User.LastName + " has been updated successfully!");
                response.DataResponse = patient.PatientFileId;
                return StatusCode (200, response);
            } else {
                foreach (string error in updateUser.Errors) {
                    ModelState.AddModelError (string.Empty, error);
                }
                return BadRequest (ModelState);
            }


}

is this a wrong way to go by it?

I stumbled accross this post here, where it suggests another approach, awaiting all tasks together, 

await Task.WhenAll(stuff1Task, stuff2Task);

in my approach, I am trying to roll back the changes if one step goes wrong, I want to guarantee a correct chain of actions here, if my approach is wrong, how should I go around it?

Windows Authentication for .NET Core 2 and Angular 5

$
0
0

My front-end is running on localhost:4200 and back-end on localhost:5000 I have setup Windows Authentication on the back-end and front-end as below

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
     WebHost.CreateDefaultBuilder(args)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseStartup<Startup>()
        .Build();
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<IISOptions>(options =>
    {
        options.AutomaticAuthentication = true;
    });

    services.AddAuthentication(IISDefaults.AuthenticationScheme);

    services.AddAuthorization(options => {
            options.AddPolicy("AllUsers", policy => {
                policy.AddAuthenticationSchemes(IISDefaults.AuthenticationScheme);
                policy.RequireRole("S - 1 - 1 - 0");
            });
     });

    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
    });

   var mvcBuilder = services.AddMvc();
   mvcBuilder.AddJsonOptions(opts => opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());
  services.AddAutoMapper(typeof(Startup));
  services.AddSingleton<IConfigurationRoot>(_config);
  services.AddRouting();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole();


    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();

    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();
    DefaultFilesOptions options = new DefaultFilesOptions();
    options.DefaultFileNames.Clear();
    options.DefaultFileNames.Add("index.html");
    app.UseDefaultFiles(options);

    app.UseAuthentication();

    app.UseCors("CorsPolicy");


    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    // Route all unknown requests to app root
    app.Use(async (context, next) =>
    {
        await next();

        // If there's no available file and the request doesn't contain an extension, we're probably trying to access a page.
        // Rewrite request to use app root
        if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
        {
            context.Request.Path = "/index.html"; // Put your Angular root page here 
            context.Response.StatusCode = 200; // Make sure we update the status code, otherwise it returns 404
            await next();
        }
    });

}

On the controller,

[Authorize]
[Route("/api/service/testWinAuth")]
[EnableCors("CorsPolicy")]
public class TestWinAuth : Controller
{
 ....
}

In the method within this controller I have,

[Route("/{id}/{withVoids?}")]
[HttpGet]
[Authorize]
public Object testMethod(Int64? id, String withVoids)
{
    var userId = HttpContext.User.Identity.Name;

}

launchSettings.json

{"iisSettings": {"windowsAuthentication": true,"anonymousAuthentication": false,"iisExpress": {"applicationUrl": "http://localhost:5000/","sslPort": 0
    }
  },"profiles": {"IIS Express": {"commandName": "IISExpress","launchBrowser": true,"environmentVariables": {"ASPNETCORE_ENVIRONMENT": "Development"
      }
    },"webapi": {"commandName": "Project","launchBrowser": true,"environmentVariables": {"ASPNETCORE_ENVIRONMENT": "Development"
      },"applicationUrl": "http://localhost:5001/"
    }
  }
}

On the front-end side, I have the following settings:

proxy.conf.json

{"/api": {"target": "http://localhost:5000","secure": false
  }
}

The http request is set up to use the option withCredentials = true

get(url: string, options?: RequestOptionsArgs): Observable<Response> {
  if (!options) {
    const headers = new Headers({ 'Content-Type': 'application/json' });
    options = new RequestOptions({ headers: headers, withCredentials: true });
  }
  // noinspection TypeScriptUnresolvedFunction
  return super.get(url, options)
    .map(r => r)
    .catch((error: any): Observable<Response> =>
      this.errorDisplayAndRedirect(error));
}

When accessing the URL localhost:4200, it asks for username and password and displays the page after authenticating. When I click on a button which sends a Get request, it asks for authentication again and this time it does not authenticate and I get 401 Unauthorized error. But, When I access the back-end directly using the URL, it asks for username and password and authenticates as expected. How do I correctly pass authentication information from front-end to back-end?

Keeping modelstate - Is this bad practice?

$
0
0

So I have a web app where I have just one view where you can create and view all the entries for, for an example a "status"

I have this method to load

        public IActionResult Status()
        {
            StatusViewModel vm = new StatusViewModel
            {
                Statuses = _context.Statuses
            };

            return View(vm);
        }

and this method to create:

 public async Task<IActionResult> CreateStatus([Bind("StatusName")] StatusViewModel status)
        {
            if (ModelState.IsValid)
            {
                Status newStatus = new Status
                {
                    StatusName = status.StatusName
                };

                _context.Add(newStatus);
                await _context.SaveChangesAsync();

            }  else {
                StatusViewModel vm = new StatusViewModel
                {
                    Statuses = _context.Statuses
                };

                return View("Status", vm);
            }

            return RedirectToAction("Status");
        }

Now my questions is, is it bad practice that I pass a new statusviewmodel to my view if the modelstate is not valid? I do this to keep the modelstate, cause its not saved when used redirectToAction, so i cant just use that method again.

Could I have done this a better way or is this an okay solution?

Protect Web API - Best Method

$
0
0

Hello

Is JWT over https the best way to protect the web api or there are more secured ways?

The user will login using phone number and the phone number will be validated using OTP sent via SMS, only once, until user logs out.

Thanks

IHostedServices and site IP address

$
0
0

With .NET Core 2.1 and ASP.NET Core, you can have multiple IHostedServices running at the same time as the WebHost.

How would you determine the IP address that the WebSite is bound too from one of the other HostedServices?

I'd like to start a separate background service (IHostedService) that is used as a discovery service (SSDP), but need to know the IP address. Hardcoding the address NOT an option. I want to use whatever the web site is bound too.


Transaction Scope with Dapper in .Net Core Project

$
0
0

Hello,

 I have an ASp.net Core project . Also  I use Dapper as ORM in Data Access Layer .  How Can I Implement Transaction Scope in .net Core ?

 Thanks,

  Ibrahim

Best Practices on WebApi Localization

$
0
0

Hello:

I have a Visual Studio solution with ASPNetCore API and .Net Standard Libraries.

In .Net Standard Libraries I have some view model classes to use on server and client side (WPF Application).

I'm reading about localization on .Net core and I don't want to use IStringLocalizer and DI because I want to do localization in .Net Standard projects and in Infraestructure projects, not only in the controllers. My Resources File is in .Net Standard project.

I'm thinking in two options. Send error codes to client like "ERR_01", "USR_NOT_FOUND" ... and do localization on client. Another option is to use localization header in API requests and do localization on server side.

Someone can help me with ideas or examples to do it in the best way? With regards,

Dependency injection in Xunit project

$
0
0

Hello,

I am working on an ASP.Net Core MVC Web application.

My Solution contains 2 projects: One for the application and a second project, dedicated to unit tests.

I have added a reference to application project in Tests project.

What i want to do now is to write a class in Tests project which will communicate with database throw entity framework.

What i was used to do in application project is to access to my DbContext class through constructor dependency injection.

But i do not managed to do this in my tests project because i have no Startup.cs file. This is in this file i can declare services which will be available. So how can i do to get a reference to an instance of my DbContext in test class ?

Thanks 

Separate project for asp.net core tests

$
0
0

I am working on an asp.net core mvc application.

I have created 2 projects in the same solution:

  • My web application.
  • An Xunit Test project

I have read this is a good practice to put tests in a separate project.

I have created 2 separates git repositories (one for each project).

But i am wondering how i can write a gitlab-ci.yml file. Should i write one per project ?

Thanks

How to queue method execution in asp.net core

$
0
0

I created messenger which uses AT commands and GSM modem to communicate but if many users send and receive messages at one time then AT commands will overlap and that will cause a lot of problems so I thought that my web app need sort of FIFO Queue for storing send/receive method execution. 
Let's say I have HttpPost method which is executed by pressing SendMessage button on the web page this method saves the message to the database and executes SendSms and ReceiveSms method which doing stuff with AT commands as in the code below.

[HttpPost(Name = "add-message")]
    public async Task<IActionResult> PostMessage([FromBody] MessengerViewModel messengerViewModel)
    {  
        AtSmsSender smsSender = new AtSmsSender();
        InnerAtSmsReceiver innerAtSmsReceiver = new InnerAtSmsReceiver(_receivedMessagesService);

        await smsSender.SendSms(messengerViewModel.PhoneNr, messengerViewModel.MessageBody);
        await innerAtSmsReceiver.ReceiveSms();

        //Logic of saving message using service (must be in queue to)
    }

How could I queue this Http method or methods inside it that they would be stacked and executed after some delay? 

e.g. of functionality There is 20 users and they clicked send button almost in one time, so methods stacking in queue and first user message is sent and response received, after second third and so on. Users wont chat with other people but with device which response is pretty fast

Viewing all 9386 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>